C program and Makefile on how to build, insert and remove kernel module from linux

Install Linux headers, if not present

apt-get install build-essential linux-headers-$(uname -r)

1. Create C file


Neelkanth_98$ cat hello.c

#include <linux/module.h>    // included for all kernel modules
#include <linux/kernel.h>    // included for KERN_INFO
#include <linux/init.h>      // included for __init and __exit macros

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Lakshmanan");
MODULE_DESCRIPTION("A Simple Hello World module");

static int __init hello_init(void)
{
        printk(KERN_INFO "Hello world!\n");
            return 0;    // Non-zero return means that the module couldn't be loaded.
}

static void __exit hello_cleanup(void)
{
        printk(KERN_INFO "Cleaning up module.\n");
}

module_init(hello_init);
module_exit(hello_cleanup);

2. Makefile


Neelkanth_98$ cat Makefile
obj-m += hello.o

all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

3. go to root mode


Neelkanth_98$ insmod hello.ko
insmod: ERROR: could not insert module hello.ko: Operation not permitted


4. Insert Kernel Module

Neelkanth_98$ su
Password:
root@labuser-virtual-machine:/home/labuser/expt/kernel_module# insmod hello.ko
root@labuser-virtual-machine:/home/labuser/expt/kernel_module# dmesg | tail -f

[40306.769895] audit: type=1400 audit(1508466436.406:67): apparmor="STATUS" operation="profile_replace" profile="unconfined" name="/usr/sbin/cupsd" pid=2551 comm="apparmor_parser"
[1730928.739904] a.out[16081]: segfault at 0 ip 00007fd9e3d3c8d4 sp 00007fff84170350 error 4 in libc-2.19.so[7fd9e3ccf000+1be000]
[2943898.266887] a.out[25330]: segfault at 7f12277ab000 ip 00007f122737c630 sp 00007fffe59c1f28 error 4 in libpthread-2.19.so[7f122736e000+19000]
[4065779.552313] No module found in object
[4065789.694978] hello: module verification failed: signature and/or  required key missing - tainting kernel
[4066274.251052] Hello world!


5. Delete Kernel Module


root@labuser-virtual-machine:/home/labuser/expt/kernel_module# rmmod hello.ko
root@labuser-virtual-machine:/home/labuser/expt/kernel_module# dmesg | tail -f
[1730928.739904] a.out[16081]: segfault at 0 ip 00007fd9e3d3c8d4 sp 00007fff84170350 error 4 in libc-2.19.so[7fd9e3ccf000+1be000]
[2943898.266887] a.out[25330]: segfault at 7f12277ab000 ip 00007f122737c630 sp 00007fffe59c1f28 error 4 in libpthread-2.19.so[7f122736e000+19000]
[4065779.552313] No module found in object
[4065789.694978] hello: module verification failed: signature and/or  required key missing - tainting kernel
[4066274.251052] Hello world!
[4066292.255527] Cleaning up module.