Skip to content

Instantly share code, notes, and snippets.

@bluecmd
Created August 5, 2016 17:35
Show Gist options
  • Save bluecmd/ef02e8791aadbcee31e936ed51acb5de to your computer and use it in GitHub Desktop.
Save bluecmd/ef02e8791aadbcee31e936ed51acb5de to your computer and use it in GitHub Desktop.
getpwnam preload injection example
[openswitch]$ gcc -shared -fPIC getpwnam-preload.c -o getpwnam.so -ldl [~]
[openswitch]$ gcc getpwnam.c -o getpwnam [~]
[openswitch]$ ./getpwnam bluecmd [~]
name: bluecmd
uid: 1000
[openswitch]$ ./getpwnam bluecmd-test [~]
getpwnam: Success
[openswitch]$ LD_PRELOAD=$PWD/getpwnam.so ./getpwnam bluecmd [~]
name: bluecmd
uid: 1000
[openswitch]$ LD_PRELOAD=$PWD/getpwnam.so ./getpwnam bluecmd-test [~]
name: bluecmd-test
uid: 1000
#define _GNU_SOURCE
#include <string.h>
#include <sys/types.h>
#include <pwd.h>
#include <dlfcn.h>
typedef struct passwd *(*getpwnam_type)(const char *name);
struct passwd *getpwnam(const char *name) {
struct passwd *pw;
getpwnam_type orig_getpwnam;
orig_getpwnam = (getpwnam_type)dlsym(RTLD_NEXT, "getpwnam");
pw = orig_getpwnam("bluecmd");
if (pw == NULL) {
return pw;
}
pw->pw_name = strdup(name);
return pw;
}
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#include <errno.h>
int main(int argc, char *argv[]) {
errno = 0;
struct passwd *pw = getpwnam(argv[1]);
if (pw == NULL) {
perror("getpwnam");
return 1;
}
printf("name: %s\n", pw->pw_name);
printf("uid: %d\n", pw->pw_uid);
return 0;
}
@ganeshragnarayanan
Copy link

This is really cool ! Thanks for posting this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment