Created
September 20, 2016 16:25
-
-
Save bluecmd/40de8f5e664c3228f5702dc1f7993925 to your computer and use it in GitHub Desktop.
Exec hook example on how to mangle argv[0] for scripts
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 <alloca.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <dlfcn.h> | |
typedef ssize_t (*execve_func_t)(const char* filename, char* const argv[], char* const envp[]); | |
static execve_func_t old_execve = NULL; | |
int execve(const char* filename, char* const argv[], char* const envp[]) { | |
char buf[1024]; | |
FILE *f = fopen(filename, "r"); | |
size_t len = fread(buf, 1024, 1, f); | |
if (strncmp(buf, "#!/bin/sh", len) == 0) { | |
filename = "/usr/games/cowsay"; | |
size_t argc = 0; | |
for(; argv[argc] != NULL; argc++); | |
char** new_argv = alloca(argc+1); | |
memcpy(new_argv+1, argv, sizeof(char*) * (argc + 1)); | |
new_argv[0] = strdup(filename); | |
argc++; | |
argv = new_argv; | |
} | |
if (old_execve == NULL) { | |
old_execve = dlsym(RTLD_NEXT, "execve"); | |
} | |
return old_execve(filename, argv, envp); | |
} |
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
bluecmd@:~$ gcc -o exec_hook.so -shared exec_hook.c -fPIC -ldl | |
bluecmd@:~$ head /etc/init.d/motd | |
#!/bin/sh | |
### BEGIN INIT INFO | |
# Provides: motd | |
# Required-Start: hostname $local_fs | |
# Required-Stop: | |
# Should-Start: | |
# Default-Start: 1 2 3 4 5 | |
# Default-Stop: | |
# Short-Description: Create dynamic part of /etc/motd | |
# Description: /etc/motd is user-editable and static. This script | |
bluecmd@:~$ /etc/init.d/motd status | |
bluecmd@:~$ LD_PRELOAD=./exec_hook.so bash | |
bluecmd@:~$ /etc/init.d/motd status | |
_________________________ | |
< /etc/init.d/motd status > | |
------------------------- | |
\ ^__^ | |
\ (oo)\_______ | |
(__)\ )\/\ | |
||----w | | |
|| || | |
bluecmd@:~$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment