Skip to content

Instantly share code, notes, and snippets.

@valmat
Created December 1, 2022 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valmat/a9db9cba91b636e0a4c21cbf2e3c9eaf to your computer and use it in GitHub Desktop.
Save valmat/a9db9cba91b636e0a4c21cbf2e3c9eaf to your computer and use it in GitHub Desktop.
function to change process owner (if required)
#include <unistd.h>
// true if current user is not root
// or true if owner changing is not required (targ_uid == 0)
// or true if current user is root and uid changed
// false otherwise (owner changing was unsuccessful)
bool change_owner(unsigned int targ_uid) noexcept
{
return
(0u != getuid()) || // made sure that src_uid == 0 (source is root)
(0u == targ_uid) || // made sure that targ_uid != 0 (target is not root)
(0 == (setgid(targ_uid) & setuid(targ_uid))); // set the gid and then the uid and then checked the result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment