Last active
November 28, 2024 13:55
-
-
Save RaphGL/8fe7f8222f0e51522ef2ef6853827845 to your computer and use it in GitHub Desktop.
Detect what is the actual user running the comamnds. This can be used to detect if user is running sudo or running commands as any other user in the system.
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 <pwd.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
int main(void) { | |
// getuid retrieves the UID for the current user, the user can pretend to be another user, | |
// thus the UID is not necessarily attached to the current user running. | |
uid_t user_id = getuid(); | |
// getpwuid retrieves the `struct passwd` which stores many some information about the user, | |
// such as UID, GID, name, home directory, etc | |
struct passwd *userinfo = getpwuid(user_id); | |
if (!userinfo) { | |
perror("failed to get information for user"); | |
return 1; | |
} | |
// getlogin retrieves the user that logged into the system, this won't change for the entire session | |
const char *logged_user = getlogin(); | |
if (!logged_user) { | |
perror("failed to get logged user's username"); | |
return 1; | |
} | |
// getpwnam is the same as getpwuid but retrieves based on username instead of UID | |
struct passwd *logged_userinfo = getpwnam(logged_user); | |
if (!logged_userinfo) { | |
perror("failed to get logged user's information"); | |
return 1; | |
} | |
// if both users have the same UID, they're the same user | |
// otherwise we know that the user is "pretending" to be another user | |
if (logged_userinfo->pw_uid == userinfo->pw_uid) { | |
printf("running as %s\n", userinfo->pw_name); | |
} else { | |
printf("running as %s but called by %s\n", userinfo->pw_name, | |
logged_userinfo->pw_name); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment