Skip to content

Instantly share code, notes, and snippets.

@udzura
Last active August 20, 2018 06:58
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 udzura/cee5176635831303be3523b1c573fc08 to your computer and use it in GitHub Desktop.
Save udzura/cee5176635831303be3523b1c573fc08 to your computer and use it in GitHub Desktop.
clone-tarou
*.o
*.a
*.out
#define _GNU_SOURCE
#include <sys/wait.h>
#include <sched.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#define EXECVE_FAILED \
perror("execve"); \
exit(1)
int use_clone_parent = 0;
int become_jirou(void *dummy) {
char *args[] = {"clone-tarou", "jirou", NULL};
execve("/proc/self/exe", args, NULL);
EXECVE_FAILED;
}
int main(int argc, char *argv[]) {
if (argc <= 1) {
fprintf(stderr, "Usage: %s arg1 [--use-clone-parent]\n", argv[0]);
exit(1);
}
if (argc >= 3) {
if (!strcmp(argv[2], "--use-clone-parent")) {
use_clone_parent = 1;
}
}
if(!strcmp(argv[1], "parent")) {
pid_t pid = fork();
if(pid == 0) {
if(use_clone_parent) {
char *args[] = {"clone-tarou", "tarou", "--use-clone-parent", NULL};
execve("/proc/self/exe", args, NULL);
EXECVE_FAILED;
} else {
char *args[] = {"clone-tarou", "tarou", NULL};
execve("/proc/self/exe", args, NULL);
EXECVE_FAILED;
}
} else {
while((pid = waitpid(-1, NULL, 0)) >= 0) {
printf("[!] exit: PID=%d\n", pid);
}
}
} else if (!strcmp(argv[1], "tarou")) {
#define STACK_SIZE (1024 * 1024)
char *stack;
char *stack_top;
stack = malloc(STACK_SIZE);
stack_top = stack + STACK_SIZE;
int flag = SIGCHLD;
if(use_clone_parent) {
flag |= CLONE_PARENT;
}
int pid = clone(become_jirou, stack_top, flag, NULL);
if((pid = waitpid(pid, NULL, 0)) >= 0) {
printf("[!] Jirou (%d) is added under tarou and exit\n", pid);
} else {
printf("[!] Hey, maybe a new sibling is added\n");
sleep(5);
}
} else if (!strcmp(argv[1], "jirou")) {
sleep(1);
system("ps axf | grep clone-taro[u] | grep -v grep");
sleep(5);
} else {
fprintf(stderr, "Invalid role: %s\n", argv[1]);
exit(1);
}
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment