LINUX : How to create a Kernel module in C language to run our code with the highest possible privilege

Today we will talk about how to create a kernel module in C language to run our code with the highest possible privilege. In some cases, it is necessary to run code with a higher privilege than root, in linux this can only be done in one way, with a kernel module. And you may ask, how can I create a kernel module? Very simple: With C language. It seems much more difficult than it really is, let’s go there:

To do this the first thing we must do is to create our Kernel Module C code.

The path where these files have been saved is “/tmp/test-modulo”.

The file “testmodulo.c” will contain all the module code:

linux como crear un modulo del kernel linux con c

In plain text:

// Definiendo __KERNEL__ and MODULE nos permite acceder a nivel de kernel.
root@pc#undef __KERNEL__
root@pc#define __KERNEL__
root@pc#undef MODULE
root@pc#define MODULE
// Linux Kernel/LKM headers: module.h es necesario para todos los modulos y kernel.h 
//y tambien para para KERN_INFO.
root@pc#include <linux/module.h>    // Incluido para todos los modulos de kernel
root@pc#include <linux/kernel.h>    // Incluido para KERN_INFO
root@pc#include <linux/init.h>        // Incluido para __init y __exit macros

static int __init testmodulo_init(void)
{
   printk(KERN_INFO "testmodulo cargado\n"); //Se loga en el log del sistema
   //Aqui iria el codigo a ejecutar
   return 0;    // Si el retorno no es 0 
                //quiere decir que el modulo no se ha podido cargar
}

static void __exit testmodulo_cleanup(void)
{
   printk(KERN_INFO "Informacion de cleanup\n"); //se loga en el /var/log/messages
}
module_init(testmodulo_init);
module_exit(testmodulo_cleanup);

The “Makefile” file, with which we specify the compilation options:

obj-m := testmodulo.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
	$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
	$(MAKE) -C $(KDIR) M=$(PWD) clean

To compile and use the module you have to do the following from the console:

Go to the directory:

root@pc#cd /tmp/test-modulo

We compile with make and gcc:

root@pc#make

Now testmodulo.ko should exist

root@pc#ls /tmp/test-modulo/testmodulo.ko
testmodulo.ko

Install the module

root@pc#sudo insmod /tmp/test-modulo/testmodulo.ko
root@pc#

We check if it has been loaded

root@pc# cat /var/log/messages|grep testmodulo -i
Apr  9 20:52:21 sysger kernel: [15604.644410] testmodulo: module license 'unspecified' taints kernel.
Apr  9 20:52:21 sysger kernel: [15604.644859] testmodulo cargado
root@pc# lsmod|grep testmodulo
testmodulo                  192232  0

And with this we would have everything ready to use our new module.

Thank you very much for visiting the blog! If you liked it, don’t forget to leave a comment and share the article.

Leave a Reply