How to use setuid() from root to become user, with the possibility of becoming root again later?
c, linux, root, security, setuid
Solution
`seteuid(some random uid)` to drop privileges, `seteuid(0)` to get them back, when running as `root`.
Problem
I'm trying to do the safe thing, and have a program that needs to runs as root to drop its privileges when it doesn't need them. This works well if I `chmod` my binary with the SUID bit, and make it belong to root, as now I have UID = some user, and EUID = root, so I can use `seteuid(0)` and `seteuid(getuid())` to respectively raise and drop admin rights. But if I use `sudo` instead of setting the SUID, then UID == EUID == 0, and so calling `seteuid(getuid())` won't have any effect. And I can't just change `UID` to some value from some random user, as the `setuid()` man page clearly states that if it is called from a program running as root, one loses the privileges for good, with no hope of getting them back. So, how do I make my program lose temporarily its privileges when run using `sudo`?