Last active
September 14, 2024 19:06
-
-
Save mid-kid/e9c7b9a3bee109af90befd45089e2a2f to your computer and use it in GitHub Desktop.
Disable ASLR in linux executable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Disable ASLR in linux executable | |
// | |
// This bit of code will disable ASLR when it's linked into a linux executable. | |
// It's achieved by setting the process personality (ADDR_NO_RANDOMIZE), | |
// and re-executing itself. | |
// | |
// This can be used on programs that are built from source, as well as on | |
// existing dynamically linked executables through LD_PRELOAD. | |
// | |
// Usage (linked statically with program): | |
// cc -o noaslr.o -c noaslr.c | |
// cc -o myprog.o -c myprog.c | |
// cc -o myprog myprog.o noaslr.o | |
// ./myprog | |
// | |
// Usage (with precompiled binary through LD_PRELOAD): | |
// cc -shared -o noaslr.so noaslr.c | |
// LD_PRELOAD="$PWD/noaslr.so" ./myprog | |
#ifdef __linux__ | |
#include <unistd.h> | |
#include <sys/personality.h> | |
__attribute__((constructor)) | |
static void _(int argc, char **argv, char **envp) | |
{ | |
int pers = personality(0xffffffff); | |
if (!(pers & ADDR_NO_RANDOMIZE) && | |
personality(pers | ADDR_NO_RANDOMIZE) != -1) { | |
execve("/proc/self/exe", argv, envp); | |
} | |
} | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example program to test ASLR | |
// Prints out the pointers of a few kinds of allocations | |
// Compare output with and without GCC's -no-pie option, and noaslr.c | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/mman.h> | |
int func(void) { | |
return 0; | |
} | |
int main() { | |
void *mapmem = mmap(NULL, 0x100, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
void *brkmem = sbrk(0x100); | |
void *mem = malloc(0x100); | |
char sptr[0x100]; | |
int (*fptr)() = func; | |
printf("%p %p %p %p %p\n", mapmem, brkmem, mem, sptr, fptr); | |
return fptr(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment