简体   繁体   中英

How do I change linux user within C code?

How do I change the user that my c program identifies itself as?

A command-line tool I want to invoke automatically requires to be run as a specific user and won't work otherwise.

I have tried using setuid(0) but I still don't get the desired results.

The user I want to imitate is not ' root ', but a normal unprivileged, shell-less user. I want to be able to run the binary logged in as the user nobody. I was able to concoct a solution as 'root' using:

su -ls /bin/bash -c /binary (superuser)

However I want to be able to achieve the same logged in as user nobody

Is there something I'm missing?

If anyone could just become root by putting setuid(0); in their program, Unix would be, well, Windows.

Some thoughts:

  1. Running external command line tools from C is almost always a mistake.
  2. If you really need this command line tool, does the tool really need root permission to work? If not, fix the tool (or go back to step 1 and incorporate the functionality into your own program).
  3. If you really need the tool and it really needs root, consider setting up sudo permissions for it and running it via sudo.

Given the very basic question you're asking, you should not even attempt to write code that will run as root, so I've omitted any details about how to setup root permissions for your program.

You don't need to do anything on the C side. Just change the binary to be owned by the user you want to use, enable the setuid bit in the binary ( chmod u+s ), and you're all set!

(If you don't want any user to be able to run as your designated user willy-nilly, consider using sudo.)

To change the current userid:

Firstly, lookup the new userid using getpwnam() . This returns a struct passwd *pw and a NULL value will indicate that user doesn't exit. The struct contains the userid ( pw_uid ) and the group id ( pw_gid ) which are needed to perform the change.

if((pw = getpwnam(userid)) == NULL) sprintf(error_msg "Userid '%s' does not exist", userid);

Then set the group id for the new user

if (setgid(pw->pw_gid) != 0) sprintf(error_msg "setgid() to %d failed", pw->pw_gid);

Finally, set the user id for the new user

if (setuid(pw->pw_uid) != 0) sprintf(error_msg "setuid() to %d failed", pw->pw_uid);

Error recovery during this process is messy. The easiest way is to simply abort if either setgid() or setuid() fails. The real problem occurs if changing the group succeeds, but changing the user fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM