Search code examples
shellbuffer-overflowshellcode

The address of an environment variable changes every time it is checked


I'm trying to learn how to use buffer overflow to change the address in esp to run a shell code; and I've defined a environment variable called "SHELLCODE" to store execution of the shell code, but whenever I run getenv function to get the address of that environment variable, the address changes overtime;

Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff507b9bd5
Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff5fb4abd5
Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff54ca5bd5
Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff5d633bd5
Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff50bedbd5
Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff5d5f9bd5
Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff5bc6ebd5
Onurcans-MacBook-Air:ArtofExploitation onurcanbektas$ ./genenv_exp SHELLCODE
SHELLCODE is at 0x7fff5589bbd5

What is the reason for that ?, and how can one prevent this from happening ?


Solution

  • It seems that your program is compiled to use Address Space Layout Randomization (ASLR). On every execution of your program, major memory sections (such as your code, globals, stack, etc.) are being mapped to a randomized memory address. Thus, the address "moves" every time you execute your program.

    I would advice you to check if you can turn off ASLR for your program, by compiling it to use fixed addresses. Another option could be to temporarily disable ASLR for your PC (which isn't recommended, because users typically forget to turn it on afterwards).

    Another trick I often use, since it is an exercise, is to "leak" the address you want to use manually. Add a print line to your program to print the wanted address, and only then wait for input that will overflow the program. By making your exploit parametric on the address, you will be able to exploit the exercise (simulating a real word case in which you need a memory leak for your attack to work).

    For example (taken from the test module of scout):

    printf("The buffer is at address: %p\n", buffer);
    printf("Press ENTER to continue\n");
    fgetc(stdin);