File is cleared after preventing writing to it by hooking sys_write

67 Views Asked by At

I want to create a kernel module which prevents even root from writing to a specific file(as long as he doesn't know about the kernel module preventing it). So what I am doing is I hook sys_write via Ftrace and if the name of the file which is written to matches the predefined filename, the correct return value is returned(the number of bytes the caller wanted to write), though without calling the actual syscall. For all other files, the actual syscall is called. I do not do anything else with the file descriptor. I don't have a problem with this functionality, it works fine. But whenever writing to a file is successfully prevented via this method, it results in the file content being removed completely(or maybe just the old file(with content) being overwritten with a completely new file(without content), I'm not sure about that part).

The code of the sys_write hook(orig_write is a function pointer to sys_write):

static asmlinkage long my_write(const struct pt_regs *regs){

    unsigned int fd = (unsigned int)regs->di;

    struct task_struct* task = current;

    struct file* opened_file = task->files->fdt->fd[fd];
    

    if(opened_file){

        if(strcmp(opened_file->f_path.dentry->d_name.name, "authorized_keys") == 0){

            pr_info("Preventing write...\n");
            return regs->dx;

        }

    }else{
        pr_info("FD is ZERO\n");
    }
    
    return orig_write(regs);

}

I tried using different applications to write to the file and traced all of them, so I'm pretty confident that it's not them causing this problem but rather something within the Linux kernel. I also know that this problem is not specific to hooking sys_write, because as another approach I hooked sys_openat and if a specific file was opened I modified the mode of the returned file descriptor so that it was not in write-mode(which also worked well). But here too, the file-content is cleared.

I have absolutely no idea what that could be and why that could be happening. It would be great to at least know what is causing this to prevent it from happening, but at this point I don't have any idea what to try to even find out what this is caused by, so any idea how I could go about with this is welcome :)

My test system:

Ubuntu 22.04.3 LTS

Kernel 6.2.0-34-generic

Via VirtualBox 7.0.8 on Windows 10

0

There are 0 best solutions below