Linux Kernel runtime unpacker and binary signature

Mach-Os and IOs have implemented a runtime unpacker and signature verification when binaries are exectued.
This allows to check if the binary is approved by Apple and make it more complicated to reverse (We need to dump the memory).
In this short note, we will see what can be done on Linux with this same implementation. I have implemented a runtime unpacker for
the ndh2k13 CTF (crackme300) when a binary is loaded in memory. When reversing the binary, you can see that the TEXT section
is packed, as shown below:

Now, to unpack the binary when it is executed on the Operating System, we need to patch the kernel source. When a binary
is executed, the load_elf_binary function is called. This function setups all VMA and is the one that needs to be changed.
First of all, we need to know if the binary is packed or not. To do that I decided to put a flag in the ELF header.

$ readelf -h ./crackme.packed | grep "Flags"
Flags: 0x20
$

When the ELFHeader.flags values 0x20 the binary is packed, otherwise it is not. In the load_elf_binary function we check if
the binary has this flag.

You can found the complete patch to Linux 3.7.10 here.
Currently, this implementation is not really ideal because the packing algorithm is not satisfying. And we cannot verify that the binary is signed. Recently RedHat
commited some tools in Linux crypto API to manipulate RSA (patch) and their works on modsign
feature. You can found his work on his
repository.

Currently, this patch just signs Linux modules but that would be nice if the system could check the signature and decrypt the binary.
In this context, the Kernel embeds the public key and when the load_elf_binary function is called, it check the signature
and decrpyts the binary. This mechanism prevents anyone, except the developpers, from compiling and signing the binary.
Maybe it will be useful in embedded system. I will try to implement it.