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

前端 未结 4 1161
借酒劲吻你
借酒劲吻你 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:56
    #include <unistd.h> // getuid
    #include <stdio.h> // printf
    
    int main()
    {
        if (getuid()) printf("%s", "You are not root!\n");
        else printf("%s", "OK, you are root.\n");
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-05 11:57

    What you really want to check for is if you have the right capability set (CAP_SYS_NICE I think is the capability you need) see man pages capabilities (7) and capget (2) this way it won't error out if you have the ability to do what you want, but you aren't root.

    0 讨论(0)
  • 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 <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".

    0 讨论(0)
  • 2021-01-05 12:11

    I would recommend NOT making this change, but instead improving your error message. It's doubtful that your application actually needs to "be root"; instead it needs certain privileges which root has, but which operating systems with fine-grained security controls might be able to grant to the application without giving it full root access. Even if that's not possible now, it may be possible 6 months or 2 years from now, and users are going to be irritated if your program is refusing to run based on backwards assumptions about the permission model rather than just checking that it succeeds in performing the privileged operations it needs to.

    0 讨论(0)
提交回复
热议问题