Skip to content

Instantly share code, notes, and snippets.

@linuxthor
Last active September 16, 2020 18:29
Show Gist options
  • Save linuxthor/427bfeb915f65d3dfbac0de637e14f31 to your computer and use it in GitHub Desktop.
Save linuxthor/427bfeb915f65d3dfbac0de637e14f31 to your computer and use it in GitHub Desktop.
Copy kernel module function and execute
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/uaccess.h>
unsigned long *amem;
static void enable_page_protection(void)
{
unsigned long value;
asm volatile("mov %%cr0, %0" : "=r" (value));
if((value & 0x00010000))
return;
asm volatile("mov %0, %%cr0" : : "r" (value | 0x00010000));
}
static void disable_page_protection(void)
{
unsigned long value;
asm volatile("mov %%cr0, %0" : "=r" (value));
if(!(value & 0x00010000))
return;
asm volatile("mov %0, %%cr0" : : "r" (value & ~0x00010000));
}
unsigned long __imf(void)
{
asm("movq amem, %rbx");
asm("movq (%rbx), %rbx");
asm("inc %rbx");
asm("inc %rbx");
asm("movq amem, %rcx");
asm("movq %rbx, (%rcx)");
asm("mov amem, %rbx");
asm("mov %rbx, %rax");
asm("pop %rbp");
asm("ret");
}
int init_module(void)
{
unsigned long diff;
void *code;
unsigned long (*ime)(void);
unsigned long gdata = 0x444f4f4b;
// allocate memory for data & copy it
amem = kmalloc(sizeof(unsigned long), GFP_KERNEL);
memcpy(amem, &gdata, sizeof(unsigned long));
// allocate memory for code & copy it
diff = ((unsigned long)&init_module - (unsigned long)&__imf);
code = __vmalloc(diff, GFP_KERNEL|__GFP_NOWARN, PAGE_KERNEL);
memcpy(code, &__imf, diff);
// you could map PAGE_KERNEL_EXEC.. or you *could* map as
// PAGE_KERNEL and disable NX if you are feeling saucy
disable_page_protection();
//dnx = (void *)kallsyms_lookup_name("disable_nx");
//*(dnx) = 1;
__supported_pte_mask &= ~_PAGE_NX;
enable_page_protection();
ime = code;
printk("IT'S SOME OK %s\n", (char *)ime());
return 0;
}
void cleanup_module(void)
{
// nothing happens here so memory remains allocated
}
MODULE_AUTHOR("linuxthor");
MODULE_LICENSE("GPL");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment