Skip to content

Instantly share code, notes, and snippets.

@laomaiweng
Last active January 11, 2024 14:40
Show Gist options
  • Save laomaiweng/d73a31be98292dc8ffe3d25283fac214 to your computer and use it in GitHub Desktop.
Save laomaiweng/d73a31be98292dc8ffe3d25283fac214 to your computer and use it in GitHub Desktop.
fake getpwuid home dir with LD_PRELOAD
/*
* Force the home directory for polluters that bypass $HOME with `getpwuid`.
* To use, set your desired $HOME and LD_PRELOAD this library.
*
* Compile with:
*
* gcc -O2 -Wall -Wextra -shared -fPIC -ldl -o libfakehome.so fakehome.c
*
*/
#define _GNU_SOURCE 1
#include <dlfcn.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
struct passwd *getpwuid(uid_t uid) {
static struct passwd fake;
char *fake_home = getenv("HOME");
struct passwd *(*real_getpwuid)(uid_t) = dlsym(RTLD_NEXT, "getpwuid");
struct passwd *pwentry;
pwentry = real_getpwuid(uid);
if (uid != getuid()) {
return pwentry;
}
if (pwentry == NULL || fake_home == NULL) {
fprintf(stderr, "Failed to fake home directory.\n");
return NULL;
}
fake = *pwentry;
fake.pw_dir = fake_home;
fprintf(stderr, "Faking home directory: %s\n", fake.pw_dir);
return &fake;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment