Skip to content

Instantly share code, notes, and snippets.

@Phantomn
Forked from apsun/hax.c
Last active March 9, 2022 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Phantomn/0b43f66e6adb24cd8e82ce2dcf1b4182 to your computer and use it in GitHub Desktop.
Save Phantomn/0b43f66e6adb24cd8e82ce2dcf1b4182 to your computer and use it in GitHub Desktop.
Hook main() using LD_PRELOAD
/*
* LD_PRELOAD를 사용하여 main()을 연결하세요. 왜 안되나요?
* 이 코드는 포터블하지 않다. 사용할때 리스크는 자신이 감당해라.
*
* Compile using 'gcc hax.c -o hax.so -fPIC -shared -ldl'
* Then run your program as 'LD_PRELOAD=$PWD/hax.so ./a.out'
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
/* 실제 main()을 위한 트램펄린 */
static int (*main_orig)(int, char **, char **);
/* __libc_start_main()에 의해 호출되는 가짜 main() */
int main_hook(int argc, char **argv, char **envp)
{
for (int i = 0; i < argc; ++i) {
printf("argv[%d] = %s\n", i, argv[i]);
}
printf("--- Before main ---\n");
int ret = main_orig(argc, argv, envp);
printf("--- After main ----\n");
printf("main() returned %d\n", ret);
return ret;
}
/*
* 실제 main 함수를 후크 버전으로 대체하는 __libc_start_main()용 래퍼.
*/
int __libc_start_main(
int (*main)(int, char **, char **),
int argc,
char **argv,
int (*init)(int, char **, char **),
void (*fini)(void),
void (*rtld_fini)(void),
void *stack_end)
{
/* 실제 메인함수 주소 저장 */
main_orig = main;
/* 실제 __libc_start_main() 찾기 ... */
typeof(&__libc_start_main) orig = dlsym(RTLD_NEXT, "__libc_start_main");
/* ... 그리고 커스텀 메인 함수로 호출 */
return orig(main_hook, argc, argv, init, fini, rtld_fini, stack_end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment