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

前端 未结 4 1170
借酒劲吻你
借酒劲吻你 2021-01-05 11:34

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:

<         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-05 11:58

    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 
    #include 
    
    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".

提交回复
热议问题