Thread: How to remove elevated privileges?

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    121

    How to remove elevated privileges?

    Hi,

    I created a program that needs to be run as root or with `sudo`. In the program, I need to use `execv` to run another program, after forking a new process. I have the following:

    Code:
    // Fork the process.
        switch((pid = fork()))
        {
            case -1: // Error.
                fprintf(stderr, "%s: %s error: fork failed (%s)\n", program_name, __func__, strerror(errno));
                exit(EXIT_FAILURE);
            case 0: // Child.
    // Remove root privileges.
                if(setuid(atoi(getenv("SUDO_UID"))) == -1)
                {
                    fprintf(stderr, "%s: %s error: setuid failed (%s)\n", program_name, __func__, strerror(errno));
                    exit(EXIT_FAILURE);
                }
    
    // Proof the UID changed.
    printf("2ID: %d\n", atoi(getenv("SUDO_UID")));
    
    // Execute external program.
                if(execl(program, program, (char  *) NULL) == -1)
                {
                    fprintf(stderr, "%s: %s error: execl failed (%s)\n", program_name, __func__, strerror(errno));
                    exit(EXIT_FAILURE);
                }
        }
    But the program that is executed lists a bunch of errors because it is not supposed to be run as root.

    How can I execute an external program with the original users UID?

    **EDIT:
    Upon further investigation, it seems it is changing the UID to the original user. The problem seems to stem from the $HOME directory the external program tries to use for reading/writing files. It is trying to use the files under root instead of the user.
    Last edited by Yonut; 02-13-2022 at 01:27 PM.

  2. #2
    Registered User
    Join Date
    Apr 2019
    Posts
    121
    Looks like it was using $HOME which was set when sudo was used. The following fixed the problem:
    Code:
    // Get the users home directory.
        pw = getpwuid(atoi(getenv("SUDO_UID")));
    // Change home directory back to the user and not root.
        setenv("HOME", pw->pw_dir, 1);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Limit process privileges
    By Sfel in forum Windows Programming
    Replies: 26
    Last Post: 06-14-2009, 11:26 PM
  2. Obtaining User Info/privileges
    By smboucou in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2008, 09:39 PM
  3. mount privileges lost
    By Mario F. in forum Tech Board
    Replies: 12
    Last Post: 10-09-2008, 05:58 AM
  4. Privileges problem
    By 3saul in forum Linux Programming
    Replies: 6
    Last Post: 04-04-2006, 06:31 AM
  5. Windows 2000 privileges
    By afreedboy in forum Tech Board
    Replies: 3
    Last Post: 07-01-2004, 08:48 AM

Tags for this Thread