Search code examples
linuxmodulelinux-kernelcross-compiling

How to compile a linux kernel module for different linux kernel


I am sort of new to kernel programming, but i have been struggling a ton with this issue for days now. I have a machine with linux kernel '5.10.0-kali7-amd64' and im using it for development of a linux kernel module for Ubutnu 16.04.4 '4.4.0-119-generic', but i can't figure out any way that i can compile it on my machine for that version and for it to actually work on the 4.4.0 kernel machine.

The closest i've got is this:

  1. I downloaded source from https://launchpad.net/ubuntu/xenial/+package/linux-headers-4.4.0-119 and installed with dpkg
  2. I then downloaded and installed the 4.4.0-119-generic from https://www.ubuntuupdates.org/package/core/xenial/main/updates/linux-image-4.4.0-119-generic
  3. Both of them installed with no issue.
  4. I compiled my module by using in my Makefile make -C /lib/modules/4.4.0-119-generic/build M=$(PWD) modules which also worked and compiled my hello world module.

However when uploaded to the 4.4.0 machine the insmod errored saying insmod: ERROR: could not insert module rootkitMy.ko: Invalid module format. The dmesg says: module: rootkit: Unknown rela relocation: 4 I then compiled my source code on the 4.4.0 machine and created a module with literally the exact same modinfo, but that one did work. here are the modinfos for both:

filename:       /rootkit.ko
version:        0.01
description:    Rootkit hook
author:         Bl4ckC4t
license:        GPL
srcversion:     46604268C8D1B7FA5115CB4
depends:        
vermagic:       4.4.0-119-generic SMP mod_unload modversions retpoline 



filename:       /rootkitMy.ko
version:        0.01
description:    Rootkit hook
author:         Bl4ckC4t
license:        GPL
srcversion:     46604268C8D1B7FA5115CB4
depends:        
vermagic:       4.4.0-119-generic SMP mod_unload modversions retpoline 

rootkitMy.ko was compiled on the 5.10 machine and didn't work while the rootkit.ko was compiled on the 4.4.0 machine and did work properly when injected with insmod What can I do to compile a working module from my 5.10 machine?


Solution

  • I managed to resolve the issue. Unknown rela relocation: 4 is an insmod error you get due to a change in the way the kernel handles PLT, more specifically the R_X86_64_PC32 and R_X86_64_PLT32. With binutils >= 2.31, the linker has decided to use R_X86_64_PLT32 relocations, which aren't supported in the older kernel.

    To fix this:

    1. I downloaded an older version of binutils (2.26.1) from https://ftp.gnu.org/gnu/binutils/
    2. extracted the folder from the archive
    3. compiled the binutils to /usr/local/binutils-2.6 by running
    ./configure --prefix=/usr/local/binutils-2.6
    make
    sudo make install
    
    1. exported the new binutils to my path and recompiled my module export PATH=/usr/local/binutils-2.6/bin:$PATH

    And now it works!