Tuesday, January 25, 2011

Access any memory by using kernel module

If you write a user program, it cannot read all the memory.

userprogram:
    virtualAddr = 0xc0010203 // randomly define virtual address
    for(i = 0; i< SIZE; i++)
    printf("%x", *(char*)(virtualAddr+i));

This program will give your segmentation fault when you run it.
Remember, CPU only understand virtual address.

Solution, write a kernel module to access any memory

#include <linux/module.h>
#include <linux/init.h>
#include <asm/io.h>

// 1G = 0x40000000
// trusted OS kernel code physical address is (0x400000, 0x620de5)
// add 1G, then test if it could access from this untrusted OS
#define PHYSTARTADDR 0x40400000
#define PHYENDADDR 0x40620de5
// this is the virtual address of kernel code
#define VIRSTARTADDR 0xc0400000
#define VIRENDADDR 0xc0620de5
#define SIZE 100

MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)
{
    char mem[SIZE];
    int i;
    void *virtualAddr ;
//  if we want to access the memory range beyond current DIMM
//  we could use ioremap to create the pagetables, so cpu will understand
//  this virtual address.
//  virtualAddr = ioremap(PHYSTARTADDR, SIZE);
//  this case, we just want to read all the current memory range, 
//  which is DIMM has been initialized.
    virtualAddr = VIRSTARTADDR;

    for(i = 0; i< SIZE; i++)
    printk("%x", *(char*)(virtualAddr+i));
 
    printk("\nhello, world\n");
    return 0;
}
static void hello_exit(void)
{
    printk("Goodbye, crule world\n");
}
module_init(hello_init);
module_exit(hello_exit);

No comments: