/** Stack Clash kernel "stack gap" patch tester * * WTFPLv2 - do whatever the fuck you want with this * Dominique Martinet * * gcc -o teststackclash teststackclash.c && ./teststackclash */ #include #include #include #include #include #include #define MMAP_OFFSET (1024*1024) int main(int argc, char argv[]) { void *stackedge, *stackaddr, *mmapaddr; char ispresent; printf("Address within stack: %p, looking for stack start edge...\n", &stackedge); stackedge = (void*)((uintptr_t)&stackedge & 0xfffffffffffff000); while (mincore(stackedge, 1, &ispresent) == 0) stackedge -= 4096; if (errno != ENOMEM) { printf("unexpected mincore errno: %d\n", errno); return -1; } printf("Stack starts here: %p, doing mmap largely before it (%p)\n", stackedge+4096, stackedge-MMAP_OFFSET); errno = 0; mmapaddr = mmap(stackedge-MMAP_OFFSET, 4096, PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, 0, 0); if (mmapaddr == MAP_FAILED) { printf("mmap failed: %d\n", errno); return -1; } if (mmapaddr != stackedge - MMAP_OFFSET) { printf("mmap ok, but didn't respect MAP_FIXED hint: %p\n", mmapaddr); return -1; } printf("mmap ok, allocating within stack until it grows (should crash with that mmap)\n"); while ((stackaddr = alloca(4096)) > stackedge); // ((char*)mmapaddr)[0] = 1; // actually didn't even need to write in map printf("Didn't crash, stack gap guard <1MB or didn't care about our map\n"); return 0; }