Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from mmaped NULL pointer

Check this code:

#include <sys/mman.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    char *addr = mmap(NULL, 6, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
    if (addr == MAP_FAILED) {
        perror("mmap");
        return 1;
    }
    strcpy(addr, "abcxyz");
    printf("Mapped into addr=0x%X\n", addr);
    printf("%s\n", addr);
    printf("%s\n", NULL);
}

fd is file descriptor to a file which contain string abcxyz I expected the program should recieve SIGSEGV upon accessing to NULL pointer But ironically, I got

Mapped into addr=0x0
abcxyz
abcxyz

What is happened? Why is it possible to map a accessible data to address NULL? With this behavior, how can I use it to exploit the system?

Note that: The program has to run under root privilege.

Note2: The behavior is produced on Linux XXXXXX 4.4.0-174-generic #204-Ubuntu SMP Wed Jan 29 06:41:01 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

like image 540
Silver Avatar asked Oct 26 '25 07:10

Silver


1 Answers

What is happened?

Usually, there's no page mapped at 0x0, so dereferencing a null pointer segfaults. But you explicitly mapped a page there, so it doesn't segfault anymore.

Why is it possible to map a accessible data to address NULL?

You answered your own question without realizing it:

Note that: The program has to run under root privilege.

The vm.mmap_min_addr sysctl normally prevents this by being set to something above 0. However, that sysctl doesn't apply to processes running as root.

With this behavior, how can I use it to exploit the system?

You can't, because if you can do that mmap, then you're already on the other side of the airtight hatchway.

By the way, your code is technically Undefined Behavior, since you're still dereferencing NULL even though there is something there. And in fact, with most common libcs, it's only the compiler's optimization of printf to puts that makes it work at all.

like image 130
Joseph Sible-Reinstate Monica Avatar answered Oct 28 '25 20:10

Joseph Sible-Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!