Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my C/C++ application determine if the root user is executing the command?

Tags:

c++

c

linux

root

I am writing an application that requires root user privileges to execute. If executed by a non root user, it exits and terminates with a perror message such as:

    pthread_getschedparam: Operation not permitted

I would like to make the application more user friendly. As part of its early initialization I would like it to check if it is being executed by root or not. And if not root, it would present a message indicating that it can only be run by root, and then terminate.

like image 262
John Rocha Avatar asked Jul 09 '10 15:07

John Rocha


People also ask

How do you check if a user is a root user?

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.

How do I know if a process is running as root?

It displays all the process running by root user. Syntax: ps -U root -u root u.

How do I know if user is root or sudo?

"sudo" is a command which allows ordinary users to perform administrative tasks. "Sudo" is not a user. Long answer: "root" (aka "superuser") is the name of the system administrator account.


1 Answers

getuid or geteuid would be the obvious choices.

getuid checks the credentials of the actual user.

The added e in geteuid stands for effective. It checks the effective credentials.

Just for example, if you use sudo to run a program as root (superuser), your actual credentials are still your own account, but your effective credentials are those of the root account (or a member of the wheel group, etc.)

For example, consider code like this:

#include <unistd.h>
#include <iostream>

int main() { 
    auto me = getuid();
    auto myprivs = geteuid();


    if (me == myprivs)
        std::cout << "Running as self\n";
    else
        std::cout << "Running as somebody else\n";
}

If you run this normally, getuid() and geteuid() will return the same value, so it'll say "running as self". If you do sudo ./a.out instead, getuid() will still return your user ID, but geteuid() will return the credentials for root or wheel, so it'll say "Running as somebody else".

like image 133
Jerry Coffin Avatar answered Sep 19 '22 21:09

Jerry Coffin