Skip to content
Advertisement

C code to access environment variables

I created an environment variable SHELLCODE which contains a 200-byte long NOP sled and a shellcode. It is stored at 0x7fffffffe285, but I’ll try to access 0x7fffffffe2e5, which is around the middle of the NOP sled.

Then I wrote the following code to try to access the variable.

#include <stdlib.h>

int main() {
    char *pointer = 0x00007fffffffe2e5;
    printf("%sn", *pointer);
}

I used gdb to see the memory

(gdb) list 1
1   #include <stdio.h>
2   
3   int main() {
4       char *pointer = (char *) 0x00007fffffffe2e5;
5       printf("%sn", *pointer);
6   }
(gdb) break 5
(gdb) run
(gdb) p pointer
$1 = 0x7fffffffe2e5 '220' <repeats 119 times>, "613006133361ə260244̀jvXQh//shh/bin211343Q211342S211341̀"
(gdb) p *pointer
$2 = -112 '220'
(gdb) p/x *pointer
$3 = 0x90
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a5bcc0 in _IO_vfprintf_internal (
    s=0x7ffff7dd2620 <_IO_2_1_stdout_>, format=<optimized out>, 
    ap=ap@entry=0x7fffffffdc58) at vfprintf.c:1632
1632    vfprintf.c: No such file or directory.

The pointer was clearly pointing to the middle of the NOP sled, and gdb could access and see what was at that address. But I keep getting this Segmentation fault error.

Is this because C programs are not allowed to access memory where environment variables are stored? If so, is there a way to allow it to access the memory?

I’m using Ubuntu 16.04 and gcc 5.4.0. Thanks in advance.

Advertisement

Answer

The getenv function is used to retrieve the values of environment variables:

const char *shellcode = getenv("SHELLCODE");
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement