Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user is root in C?

Tags:

c

unix

root

How can I verify if the user is root?

like image 700
Mohit Deshpande Avatar asked Nov 11 '10 22:11

Mohit Deshpande


People also ask

How do I find my root username?

Linux Login as Superuser Command You need to use any one of the following command to log in as superuser or root user on Linux: su command – Run a command with substitute user and group ID in Linux. sudo command – Execute a command as another user on Linux.

What is the id of root user?

The root account is the special user in the /etc/passwd file with the user ID (UID) of 0 and is commonly given the user name, root. It is not the user name that makes the root account so special, but the UID value of 0 . This means that any user that has a UID of 0 also has the same privileges as the root user.

How do I check if a Linux user has root permissions?

If you are able to use sudo to run any command (for example passwd to change the root password), you definitely have root access. A UID of 0 (zero) means "root", always. Your boss would be happy to have a list of the users listed in the /etc/sudoers file.


1 Answers

Usually it's a mistake to test if the user is root. POSIX does not even require a root user, but leaves it to the implementation to determine how permissions work. Code such as:

if (i_am_root) do_privileged_op(); else print_error(); 

will really annoy users with advanced privilege models where root is not necessary to perform the necessary privileged operations. I remember back in the early days of cd burning on Linux, I had to hack all over the cdrecord source to remove all the useless checks to see if it was running as root, when it worked just fine with permission to read /dev/sga.

Instead, you should always attempt the privileged operation you need to perform, and check for EPERM or similar if it fails to notify the user that they have insufficient privileges (and perhaps should retry running as root).

The one case where it's useful to check for root is checking if your program was invoked "suid-root". A reasonable test would be:

uid_t uid=getuid(), euid=geteuid(); if (uid<0 || uid!=euid) {     /* We might have elevated privileges beyond that of the user who invoked      * the program, due to suid bit. Be very careful about trusting any data! */ } else {     /* Anything goes. */ } 

Note that I allowed for the possibility (far-fetched, but best to be paranoid) that either of the calls to get uid/euid could fail, and that in the failure case we should assume we're suid and a malicious user has somehow caused the syscalls to fail in an attempt to hide that we're suid.

like image 61
R.. GitHub STOP HELPING ICE Avatar answered Oct 09 '22 19:10

R.. GitHub STOP HELPING ICE