Question

Alright so my question is simple but I'm kinda new to C and I was hoping someone could help me. I want to change to a different user in C. For example, I know the user's password, and if the user types: ./change user1 It will change to user1. I know this may be a security issue right now, but I'm not worried about security at the moment.

Was it helpful?

Solution

You will want to use setuid which can be found in unistd.h so it is available on POSIX systems (so any linux/unix falvour should be ok)

From the man page

If the process has appropriate privileges, setuid() shall set the real user ID, effective user ID, and the saved set-user-ID of the calling process to uid.

If the process does not have appropriate privileges, but uid is equal to the real user ID or the saved set-user-ID, setuid() shall set the effective user ID to uid; the real user ID and saved set-user-ID shall remain unchanged.

The setuid() function shall not affect the supplementary group list in any way.

here is an example

OTHER TIPS

Call the su binary (such as through system() or a combination of fork() and one of the exec functions), which knows about all the intricacies of changing credentials, both Unix-generically and on your particular OS. The terminal is shared and continues to belong to the original user.

Some of these intricacies not handled by a simple setuid() call are groups, account disabling and resource limits.

If this is just for fun, setuid() preceded by setgid() and initgroups() will probably be sufficient for you.

You have to find out the UID using getpwuid(). Afterwords you have to set the UID in your program with setuid() followed by the application/function you intent to run with these new rights, e.g. the shell. To start an application with the current UID use system().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top