Read address value from kernel using /dev/kmem

2020-05-09 09:14发布

问题:

Trying to read kernel address value (task_struct)

Wrote this code:

#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define addr 0xe6d63a80

extern int errno;

int main()
{
        int i;
        unsigned char *kmem;
        unsigned char val;

        int fd = open("/dev/kmem",O_RDWR|O_SYNC);
        if(fd < 0)
        {
                printf("Can't open /dev/kmem\n");
                return 1;
        }
        kmem = (unsigned char *) mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0xe6d63000);
        if(kmem == NULL)
        {
                printf("Can't mmap\n");
                return 1;
        }
        else
                printf("kmem=%p\n",kmem);


        return 0;
}

But it produces:

kmem=0xffffffff

Which does not look like a valid pointer to values of memory.

How to read content of kernel memory? In this case: 0xe6d63a80. I know task_struct is there, since I verified it with the debugger.

Thanks,

回答1:

That is mmap returning -1. You've assigned the value and are printingit as unsigned, though, so that is why you are seeing 0xffffffff. You should check for mmap returning and error and then check errno for the cause.

    kmem = (unsigned char *) mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0xe6d63000);
    if (kmem == MAP_FAILED) {
        perror("Error mapping memory");
        return -1;
    }

Check out the man page.