Skip to main content

🔎 Linux Kernel Module - Introduction

·332 words·2 mins· loading · loading · ·
LKM c lkm low-level
0xNinja
Author
0xNinja
mov al, 11
Table of Contents
LKM - This article is part of a series.
Part 1: This Article

How to create a basic Linux Kernel Module.

A LKM is like a .so library, and can run kernel-land.

Writting your own kernel module will help you to understand how the system works and make you think about mallocing in the kernel twice before running the code.

Code
#

Here is the bare minimum you have to code to get a working LKM:

 1#include <linux/module.h>
 2#include <linux/kernel.h>
 3
 4// Specify module licence, GPL to not taint the kernel
 5MODULE_LICENSE("GPL");
 6
 7// Called on module load
 8int init_module(void) {
 9  printk(KERN_INFO "MODULE loaded!\n");
10  return 0;
11}
12
13// Called on module unload
14void cleanup_module(void) {
15  printk(KERN_INFO "MODULE unloaded!\n");
16}

Compile
#

The Makefile I use for my modules:

 1obj-m += my_module.o
 2
 3all:
 4    sudo make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
 5
 6install:
 7    sudo insmod ./my_module.ko
 8
 9uninstall:
10    sudo rmmod my_module
11
12clean:
13    sudo make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

Then just run make. A new my_module.ko should be here, this is your kernel module.

Install
#

1sudo insmod ./my_module.ko
2# or
3make install

In dmesg you should have a new line containing MODULE loaded!. Your module is loaded in the kernel.

Uninstall
#

1sudo rmmod my_module
2# or
3make uninstall

In dmesg you should have a new line containing MODULE unloaded!. Your module is deleted form the kernel.

MISC
#

  • dmesg -C will clear the dmesg buffer
  • watch 'dmesg | grep MODULE' will append the new messages of the module so you don’t have to re-run the command

Afterwords
#

Starting to create a kernel module is pretty easy, you just have to be careful with the functions you call and how you code them. There are a lot of specific functions for the kernel only, and you must check them out before using them.

In the future I will discuss more about the internals of Linux and why using a kernel module is insanely powerfull and at the same time a pain to code.

LKM - This article is part of a series.
Part 1: This Article

Related

Draft
🔎 Creating a VM for fun - Part 2: C
·1225 words·6 mins· loading · loading
Custom VM c low-level reverse
🏌️ Binary golfing - Introduction
·711 words·4 mins· loading · loading
Binary golfing binary elf golf low-level
🏌️ BGGP3 - How to crash a famous JS engine for fun
·1571 words·8 mins· loading · loading
Binary golfing bggp low-level reverse golf js fuzz
Draft
🔎 xchg rax, rax
·1526 words·8 mins· loading · loading
assembly low-level
Draft
🔎 Creating a VM for fun - Part 1: ASM
·451 words·3 mins· loading · loading
Custom VM assembly low-level reverse
About
130 words· loading · loading