Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting address of Environmental Variable

Tags:

c

linux

shell

gdb

I have an environment variable and I'm trying to get its memory address. I have

memset(&buffer, 0x90, 517);
memcpy(&buffer[517-strlen(shellcode)],shellcode,strlen(shellcode));
setenv("EGG",buffer,1);
putenv(buffer);
printf("EGG address: 0x%1x\n", getenv("EGG"));
system("bash");

The memory address it printed out was 0x804b00c. That looked incorrect. I checked it with GDB x/x 0x804b00c. It said cannot access memory at 0x804b00c. So getenv is basically giving me garbage memory. I have called env to make sure the EGG variable was set, and it was.

Why cannot I get the memory address of EGG?

like image 287
Jake Avatar asked Dec 05 '25 08:12

Jake


1 Answers

Thanks for this question, another learning opportunity!

Have distilled your code to the following:

    #include <stdio.h>
    #include <stdlib.h>

    void main()
    {
      const char shellcode[] = "EGG=whatever";

      putenv(shellcode);

      printf("EGG address @%08X\n", getenv("EGG"));

      printf("EGG value is <%s>.", getenv("EGG"));

    }

This code works in an Eclipse/Microsoft C compiler environment. Note, I did not have to call setenv or bash or issue a system command. In this example, the environment variable EGG is set for the process.

Also, notice the difference between address of EGG and its actual value. In the first case getenv returns a char * which is a pointer to storage as defined by the %08X part of the printf statement, while %s essentially de-references the char pointer returned by getenv. Also, getenv() is found thru the #include <stdlib.h> statement.

like image 58
JackCColeman Avatar answered Dec 07 '25 22:12

JackCColeman



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!