c - Why this piece of code can get environment variable address? -
64-bit linux stack smashing tutorial: part 1 uses get environment variable address gist environment variable address. prerequisite first disable aslr via echo 0 > proc/sys/kernel/randomize_va_space
.
the content of gist is:
/* * i'm not author of code, , i'm not sure is. * there several variants floating around on internet, * 1 use. */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *ptr; if(argc < 3) { printf("usage: %s <environment variable> <target program name>\n", argv[0]); exit(0); } ptr = getenv(argv[1]); /* env var location */ ptr += (strlen(argv[0]) - strlen(argv[2]))*2; /* adjust program name */ printf("%s @ %p\n", argv[1], ptr); }
why *2
used adjust program name?
my guess program name saved twice above stack.
the following diagram https://lwn.net/articles/631631/ gives more details:
------------------------------------------------------------- 0x7fff6c845000 0x7fff6c844ff8: 0x0000000000000000 _ 4fec: './stackdump\0' <------+ env / 4fe2: 'envvar2=2\0' | <----+ \_ 4fd8: 'envvar1=1\0' | <---+ | / 4fd4: 'two\0' | | | <----+ args | 4fd0: 'one\0' | | | <---+ | \_ 4fcb: 'zero\0' | | | <--+ | | 3020: random gap padded 16b boundary | | | | | |
in diagram, ./stackdump
used execute program. can see program name ./stackdump
saved once above environment strings. , if ./stackdump
launched bash shell, bashell save in environment strings key _
:
_
(an underscore.) @ shell startup, set absolute pathname used invoke shell or shell script being executed passed in environment or argument list. subsequently, expands last argument previous command, after expansion. set full pathname used invoke each command executed , placed in environment exported command. when checking mail, parameter holds name of mail file.
environment strings above stack. program name saved time above stack.
Comments
Post a Comment