#include <linux/kernel.h> #include <linux/module.h> #include <linux/kprobes.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/pipe_fs_i.h>

#define MAX_SYMBOL_LEN 64

// static char symbol[MAX_SYMBOL_LEN] = "__do_splice"; // module_param_string(symbol, symbol, sizeof(symbol), 0644);

typedef ssize_t (*splice_fn_t)(int, loff_t *, int, loff_t *, size_t, unsigned int);

//使用S_ISFIFO宏可以判断文件是否为普通文件。 static int is_pipe(struct file *file) { return S_ISFIFO(file_inode(file)->i_mode); }

//使用S_ISREG宏可以判断文件是否为普通文件。

static int is_file(struct file *file) { return S_ISREG(file_inode(file)->i_mode); }

static int khandle_splice_entry(struct kprobe *kp, struct pt_regs *regs) { struct file *file_in = (struct file *)regs->di; struct file *file_out = (struct file *)regs->dx; int pipe_fd = (int)regs->dx; size_t len = (size_t)regs->r8;

struct task_struct * current_task = current;
struct nsproxy *ns = current_task->nsproxy;

if (!file_in || !file_out) {
    return 0;
}

// main logic   
if (is_file(file_in) && is_pipe(file_out)  && len < 100) {

    // 获取管道文件结构体的inode信息
    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;
    }

    // 取pipe_buffer结构体方法
    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){

        // 判断nsproxy 是否在容器namespace中
        // if (ns != NULL && ns->pid_ns_for_children != NULL) {
        //     printk(KERN_INFO "nsproxy for current process: %p\n", ns);
        //     printk(KERN_INFO "pid namespace for current process: %p\n", ns->pid_ns_for_children);
        //     }

        printk(KERN_INFO "[found DirtyPipe Exploit] pipebuf-flags = %X real-flag= %lx", pipe_flags , PIPE_BUF_FLAG_CAN_MERGE);

    }

}

return 0;

}

static struct kprobe my_kprobe = { .symbol_name = "__do_splice", .pre_handler = khandle_splice_entry, };

static int __init kprobe_init(void) {

int ret;
ret = register_kprobe(&my_kprobe);
if (ret < 0) {
    printk(KERN_INFO "register_kprobe failed, returned %d\n", ret);
    return ret;
}


return 0;

}

static void __exit kprobe_exit(void) { unregister_kprobe(&my_kprobe); printk(KERN_INFO "Kprobe unregistered\n"); }

module_init(kprobe_init) module_exit(kprobe_exit) MODULE_LICENSE("GPL");

抱歉,由于代码中使用了kprobe机制,无法直接将其转换为ftrace语句。ftrace和kprobe是两种不同的跟踪机制,需要不同的实现方式。如果需要使用ftrace实现类似的功能,需要重新编写代码。

Linux 内核 DirtyPipe 漏洞检测:基于 kprobe 的实现

原文地址: https://www.cveoy.top/t/topic/mSZ6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录