Created
May 17, 2014 01:34
-
-
Save winny-/1e76c3006f7c431468b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <pwd.h> | |
#define EMPTYLINE() printf("\n"); | |
void | |
sleep_forever() | |
{ | |
for (;;) | |
sleep(1); | |
} | |
void | |
show_privileges() | |
{ | |
printf("UID EUID GID EGID\n"); | |
printf("%-5d %-5d %-5d %-5d\n", getuid(), geteuid(), getgid(), getegid()); | |
} | |
/* | |
* returns 1 when some privileges may have been dropped, 0 on failure | |
*/ | |
int | |
drop_privileges() | |
{ | |
struct passwd *pw; | |
pw = getpwuid(getuid()); | |
if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid) { | |
if ((getegid() != pw->pw_gid && setgid(pw->pw_gid) < 0) || | |
setuid(pw->pw_uid) < 0) { | |
printf("Failed to drop privileges\n"); | |
} else { | |
printf("Dropped privileges...\n"); | |
} | |
return 1; | |
} else { | |
printf("Not running as different user, not dropping privileges.\n"); | |
return 0; | |
} | |
} | |
int | |
main(int argc, char *argv[]) | |
{ | |
printf("Starting sleepforever (PID %d)...\n", getpid()); | |
EMPTYLINE(); | |
show_privileges(); | |
EMPTYLINE(); | |
if (drop_privileges()) { | |
EMPTYLINE(); | |
show_privileges(); | |
} | |
sleep_forever(); | |
/* Not reached */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment