Last active
July 22, 2019 21:54
-
-
Save cteodor/e1b9846ac50e0be47e574ecc3b228a8e to your computer and use it in GitHub Desktop.
execvep vs. proc/environ
This file contains hidden or 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
#define _GNU_SOURCE | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <sys/wait.h> | |
int main(int argc, char* argv[], char* envp[]) { | |
pid_t ppid = getppid(); | |
pid_t go = 0; | |
char* envv = NULL; | |
int status; | |
if(argc > 1) { | |
go = atoi(argv[1]); | |
printf("[0] Explicit parent: %u\n", go); | |
} | |
envv = getenv("LD_PRELOAD_ME"); | |
printf("[1] Just started: me=%u, ppid=%u\n", getpid(), getppid()); | |
printf("[2] Env: LD_PRELOAD_ME=%s\n", envv ? envv : "<not-set>"); | |
if (ppid != go) { | |
printf("[3.C] After fork()/exec(). Check my /proc/%u/environ. sleeping...\n", getpid()); | |
sleep(30); | |
exit(0); | |
} | |
pid_t pid = fork(); | |
if (pid == -1) { | |
printf("Can't actually fork.Punt!\n"); | |
exit(1); | |
} else if (pid == 0) { | |
printf("[3.C] In forked child: me=%u, ppid=%u\n", getpid(), getppid()); | |
envv = getenv("LD_PRELOAD_ME"); | |
printf("[3.C] Env(pre-exec): LD_PRELOAD_ME=%s\n", envv ? envv : "<not-set>" ); | |
argv[1] = NULL; | |
if (execvpe(argv[0], argv, NULL) == -1) { | |
printf("Failed to exec.Burp!"); | |
exit(1); | |
} | |
} else { | |
printf("[3.P] In fork parent: me=%u, child=%u, ppid=%u\n", getpid(), pid, getppid()); | |
if(waitpid(pid, &status, 0) > 0 ) { | |
printf("[4] ok, child exited\n"); | |
} else { | |
printf("waitpid() failed\n"); | |
exit(1); | |
} | |
exit(0); | |
} | |
return 0; | |
} | |
# export LD_PRELOAD_ME=something-nice | |
# ./ex $$ | |
[0] Explicit parent: 1505 | |
[1] Just started: me=3527, ppid=1505 | |
[2] Env: LD_PRELOAD_ME=something-nice | |
[3.P] In fork parent: me=3527, child=3528, ppid=1505 | |
[3.C] In forked child: me=3528, ppid=3527 | |
[3.C] Env(pre-exec): LD_PRELOAD_ME=something-nice | |
[1] Just started: me=3528, ppid=3527 | |
[2] Env: LD_PRELOAD_ME=<not-set> | |
[3.C] After fork()/exec(). Check my /proc/3528/environ. sleeping... | |
[4] ok, child exited |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment