Skip to content

Instantly share code, notes, and snippets.

@haxrob
Last active August 8, 2024 03:11
Show Gist options
  • Save haxrob/5166f32c1cd22c0762fb29b4350486ec to your computer and use it in GitHub Desktop.
Save haxrob/5166f32c1cd22c0762fb29b4350486ec to your computer and use it in GitHub Desktop.
/* procscope.c
*
* Date: 2024-08-02
* Author: @haxrob https://doubleagent.net/hiding-in-plain-sight-part-2
*
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/prctl.h>
#define PROCPATHLEN 64
#define TASK_COMM_LEN 16
extern char **environ;
pid_t getpidbycomm(const char *comm) {
DIR *dir;
struct dirent *ent;
char path[PROCPATHLEN];
char buf[TASK_COMM_LEN];
int n, fd;
pid_t cpid;
pid_t me = getpid();
dir = opendir("/proc");
if (!dir) {
perror("can't open /proc");
exit(1);
}
while((ent = readdir(dir)) != NULL) {
if (!ent || !ent->d_name[0])
continue;
cpid = atoi(ent->d_name);
if (!cpid || cpid == me)
continue;
snprintf(path,sizeof(path), "/proc/%d/comm", cpid);
fd = open(path, O_RDONLY, 0);
n = read(fd,buf, sizeof(buf));
close(fd);
buf[n-1] = '\0'; // rtrim \n
if (strcmp(comm, buf) == 0) {
closedir(dir);
return atoi(ent->d_name);
}
}
closedir(dir);
return -1;
}
void clone_env(pid_t pid) {
char path[PROCPATHLEN];
char buf[2048];
char *rbuf = 0;
int fd;
int envl = 0;
int n = 0;
snprintf(path, sizeof(path),"/proc/%d/environ", pid);
fd = open(path,O_RDONLY,0);
if (fd == -1) {
perror("Can't open environ");
exit(1);
}
while ((n = read(fd,buf, sizeof(buf))) > 0) {
rbuf = realloc(rbuf, envl + n);
if (!rbuf) {
perror("unable to allocate memory");
close(fd);
exit(1);
}
memcpy(rbuf+envl, buf, n);
envl += n;
}
prctl(PR_SET_MM, PR_SET_MM_ENV_START, rbuf, 0,0);
prctl(PR_SET_MM, PR_SET_MM_ENV_END, rbuf+envl, 0,0);
}
int hook(int argc,char**argv, char**envp) {
printf("in hook().. sleeping...\n");
sleep(10000);
return 0;
}
void clearenv2() {
int len = 0;
char **env = environ;
while(*env)
len += strlen(*env++)+1;
bzero(*environ,len);
}
// alternate is to decorate hook() with __attribute__((constructor())
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)
{
char *name = basename(argv[0]);
clearenv2();
pid_t p = getpidbycomm(name);
if (p == -1) {
perror("unable to find process");
exit(1);
}
printf("cloning %d\n", p);
clone_env(p);
// here we could replace init rather then main
typeof(&__libc_start_main) orig = dlsym(RTLD_NEXT, "__libc_start_main");
return orig(hook, argc, argv, init, fini, rtld_fini, environ);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment