kernel module access user space file:
is it possible to create a file from kernel space?
is it possible to create store the data in kernel space?
Yes. its possible
source code:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
static char buf[] ="access from the kernel \n";
static char buf1[32];
int __init test_init(void)
{
struct file *fp;
mm_segment_t fs;
int result;
loff_t pos;
printk("test enter\n");
printk("KERNEL_DS=0x%llx USER_DS=0x%llx get_fs()=0x%llx\n", KERNEL_DS, USER_DS, get_fs());
fp =filp_open("/home/kishore/kernel_file",O_RDWR | O_CREAT,0644);
if (IS_ERR(fp)){
printk("create file error\n");
return -1;
}
fs =get_fs();
set_fs(KERNEL_DS); // setting the thread addr_limit to KERNEL_DS
pos =0;
printk("fp=%lx, buf=%lx get_fs()=0x%llx\n", fp, buf, get_fs());
result=vfs_write(fp,buf, sizeof(buf), &pos);
pos =0;
printk("fp=%lx, buf1=%lx \n", fp, buf1);
result=vfs_read(fp,buf1, sizeof(buf), &pos);
printk("Write contet=%s\n",buf1);
filp_close(fp,NULL);
set_fs(fs);
return 0;
}
void __exit test_exit(void)
{
printk("test exit\n");
}
module_init(test_init);
module_exit(test_exit);
MODULE_LICENSE("GPL");
Make file:
obj-m :=read_userspace.o
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
all default: modules
install: modules_install
modules modules_install help clean:
$(MAKE) -C $(KERNELDIR) M=$(shell pwd ) $@
source code for debugging purpose:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
static char buf[] ="access from the kernel \n";
static char buf1[32];
int __init test_init(void)
{
struct file *fp;
mm_segment_t fs;
int result;
loff_t pos;
printk("test enter\n");
printk("KERNEL_DS=0x%llx USER_DS=0x%llx get_fs()=0x%llx\n", KERNEL_DS, USER_DS, get_fs());
fp =filp_open("/home/kishore/kernel_file",O_RDWR | O_CREAT,0644);
if (IS_ERR(fp)){
printk("create file error\n");
return -1;
}
fs =get_fs();
//set_fs(KERNEL_DS); // setting the thread addr_limit to KERNEL_DS
pos =0;
printk("fp=%lx, buf=%lx get_fs()=0x%llx\n", fp, buf, get_fs());
result=vfs_write(fp,buf, sizeof(buf), &pos);
printk("error no=%d",result);
pos =0;
printk("fp=%lx, buf1=%lx \n", fp, buf1);
result=vfs_read(fp,buf1, sizeof(buf), &pos);
printk("error no=%d",result);
printk("Write contet=%s\n",buf1);
filp_close(fp,NULL);
//set_fs(fs);
return 0;
}
void __exit test_exit(void)
{
printk("test exit\n");
}
module_init(test_init);
module_exit(test_exit);
MODULE_LICENSE("GPL");
sources:
- https://www.programmersought.com/article/9841490505/
- https://www.spinics.net/lists/newbies/msg00861.html
- https://www.toolsou.com/en/article/200539621
- https://titanwolf.org/Network/Articles/Article?AID=0053c791-120f-47d1-9ba6-fe4313ae86a9#gsc.tab=0
- https://stackoverflow.com/questions/10810203/what-is-the-fs-gs-register-intended-for
- https://www.spinics.net/lists/newbies/msg00861.html
Comments
Post a Comment