How to change linux user in C code?

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

The command line tool that I want to call automatically should run as a specific user and will not work otherwise.

I tried to use setuid(0), but I still do not get the desired results.

The user I want to emulate is not " root ", but a regular unprivileged user without a shell. I want to be able to run a binary file registered as a user. I was able to come up with a solution as "root" using:

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

However, I want to be able to reach the same user as user no one

Is there something I am missing?

+3
source share
3 answers

You don’t have to do anything on the C side. Just change the binary file that will belong to the user you want to use, enable the setuid bit in binary format ( chmod u+s) and you are all set!

(If you do not want any user to be able to run your designated user perforce, consider using sudo.)

+3
source

If someone can just become root by adding setuid(0);to their program, Unix will, well, Windows.

Some thoughts:

  • Running external command line tools from C is almost always a mistake.
  • , root? , ( 1 ).
  • , , sudo sudo.

, , , , - , root .

+6

:

-, getpwnam(). struct passwd *pw, NULL , . struct (pw_uid) (pw_gid), .

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

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

,

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

. - , setgid() setuid(). , , .

0

Source: https://habr.com/ru/post/1781184/


All Articles