Skip to content

Instantly share code, notes, and snippets.

@AdriDevelopsThings
Created May 10, 2024 08:36
Show Gist options
  • Save AdriDevelopsThings/c5ae6e0c35c63d3c2b0667fc6b28aa3e to your computer and use it in GitHub Desktop.
Save AdriDevelopsThings/c5ae6e0c35c63d3c2b0667fc6b28aa3e to your computer and use it in GitHub Desktop.
Simple su implementation
#include <stdio.h>
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage: %s USER COMMAND [ARGS]...\n", argv[0]);
return -1;
}
char* user = argv[1];
struct passwd* passwd = getpwnam(user);
if (passwd == NULL) {
perror("error while getting user");
return -1;
}
if (setuid(passwd->pw_uid) < 0) {
perror("error while changing user");
return -1;
}
argv[argc] = 0; // args should be null terminated list
if (execv(argv[2], &argv[2]) < 0) {
perror("error while executing process");
return -1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment