I need to write (modify) an executable file and then execute it from a Linux system call. I have attempted to create (open) the file, write to it, close it, and then execute it. The problem is that the file write count is still one when attempting the execution, even though the file has been closed. Here is a snippet from the new system call, run in kernel mode, that should achieve this.
destfile = filp_open(destfilename, O_WRONLY | O_TRUNC | O_CREAT, 0755);
if (IS_ERR(destfile)) {
pr_err("Failed to open file: %s\n", destfilename);
filp_close(sourcefile, NULL);
return PTR_ERR(destfile);
}
// write data to the file
filp_close(destfile, NULL);
kernel_execve(destfilename, {destfilename, NULL}, {NULL});
The problem is that when attempting kernel_execve, the file's writecount is one, and this prevents the file being executed.
After the process that creates the file ends, the file can be executed without problems.
If I attempt to call put_write_access for the file's inode between the close and exec, the file is executed, however subsequent calls would not allow modifying the file.
call_usermodehelper().