DirtyPipe漏洞检测:使用ftrace追踪__do_splice函数
以下代码利用ftrace技术追踪Linux内核中的__do_splice函数,以检测DirtyPipe漏洞。代码通过检查管道缓冲区标志位PIPE_BUF_FLAG_CAN_MERGE,判断是否可能存在漏洞。
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/ftrace.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/pipe_fs_i.h>
static int khandle_splice_entry(unsigned long ip, unsigned long *args, struct pt_regs *regs)
{
struct file *file_in = (struct file *)args[0];
struct file *file_out = (struct file *)args[1];
size_t len = (size_t)args[4];
if (!file_in || !file_out) {
return 0;
}
// main logic
if (S_ISREG(file_inode(file_in)->i_mode) && S_ISFIFO(file_inode(file_out)->i_mode) && len < 100) {
struct pipe_inode_info *pipe = file_out->private_data;
if (!pipe) {
printk(KERN_INFO "Failed to get pipe inode info\n");
return -EINVAL;
}
unsigned int tail = pipe->tail;
unsigned int mask = pipe->ring_size - 1;
if (tail >= pipe->bufs) {
printk(KERN_WARNING "Invalid pipe buffer index\n");
return -EINVAL;
}
struct pipe_buffer *buf = &pipe->bufs[tail & mask];
if (!buf) {
printk(KERN_WARNING "Invalid pipe buffer\n");
return -EINVAL;
}
unsigned int pipe_flags = buf->flags;
// 判断是否使用了PIPE_BUF_FLAG_CAN_MERGE标志去拼接page
if (pipe_flags & PIPE_BUF_FLAG_CAN_MERGE) {
printk(KERN_INFO "[found DirtyPipe Exploit] pipebuf-flags = %X real-flag= %lx", pipe_flags, PIPE_BUF_FLAG_CAN_MERGE);
}
}
return 0;
}
static struct ftrace_hook kprobe_hook = {
.name = "kprobe_hook",
.func = khandle_splice_entry,
.is_entry = 1,
.max_args = 5,
};
static int __init kprobe_init(void)
{
int ret;
ret = ftrace_set_filter(&kprobe_hook, "__do_splice");
if (ret < 0) {
printk(KERN_ERR "ftrace_set_filter failed: %d\n", ret);
return ret;
}
return 0;
}
static void __exit kprobe_exit(void)
{
ftrace_remove_filter(&kprobe_hook);
printk(KERN_INFO "Kprobe unregistered\n");
}
module_init(kprobe_init)
module_exit(kprobe_exit)
MODULE_LICENSE("GPL");
代码说明:
- 使用
ftrace_set_filter函数注册ftrace hook,并将__do_splice函数设置为hook目标。 khandle_splice_entry函数在__do_splice函数被调用时触发,获取参数并进行判断。- 代码检查管道缓冲区标志位
PIPE_BUF_FLAG_CAN_MERGE,如果该标志位被设置,则可能存在DirtyPipe漏洞。
注意:
- 该代码仅用于检测DirtyPipe漏洞,无法修复漏洞。
- 由于ftrace需要修改内核,需要在内核编译时开启
CONFIG_FTRACE选项。
其他:
- 为了更精确地检测漏洞,可以根据具体漏洞的利用方式进一步完善代码逻辑。
- 可以使用其他内核调试工具,例如kprobe、perf等,来追踪内核函数,并进行更深入的漏洞检测和分析。
参考文档:
- https://www.kernel.org/doc/Documentation/trace/ftrace.txt
- https://www.kernel.org/doc/Documentation/filesystems/pipe.txt
本代码仅供参考,请根据实际情况进行修改和完善。
原文地址: https://www.cveoy.top/t/topic/mS0m 著作权归作者所有。请勿转载和采集!