I set my SETUID bit to a non-root user so that the process should take the ownership of that executable file always. But I figured out setuid bit can be changed back to RUID within the script itself.

Is there any way to prevent it so that setuid bit can not be changed back to its original user id ?

I tried the below experiment.

chown 1000 /usr/local/bin/php
chmod u+s  /usr/local/bin/php



echo "RUID: " . posix_getuid() . "\n";
echo "EUID: " . posix_geteuid() . "\n";
echo file_put_contents('/root/euid_root.txt', 'test');
echo "\n\n";

// return EUID to root
// a process can change it's EUID back to RUID/SUID

echo "RUID: " . posix_getuid() . "\n";
echo "EUID: " . posix_geteuid() . "\n";
echo file_put_contents('/root/uid_apache.txt', 'test');
echo "\n";

/usr/local/bin/php test.php

EUID: 1000
PHP Warning:  file_put_contents(/root/euid_apache.txt): failed to open stream: Permission denied in /root/test.php on line 17


1 Answer 1


In C, you'd do something like:

egid = getegid();
setresgid(egid, egid, egid);

euid = geteuid();
setresuid(euid, euid, euid);

to set your real, effective, and save user/group IDs to the effective one, thus preventing any future changes. You could write a simple wrapper program that did this then exec'd PHP, but actually there are a bunch of other things to consider for secure set-uid programs and thankfully wrappers already exist ... and I'm guessing the one you're looking for is Apache's suexec.

  • Is there any command like chmod by which I can set the php binary file locked to be used by the file owner only? I don't need the suexec as I am asking to set setuid for php binary not server.
    – SkyRar
    Nov 1, 2018 at 18:54
  • 1
    @SkyRar if you set php to be executable only by the owner, then the set-user-id bit would be pointless, because it sets the user id to the owner when run — which would have to be the user its already running as, since that'd be the only user permitted to run it (but chmod u=rwxs,go-rwx ["friendly" notation] or chmod 4700 [octal notation] would set that). Well, I guess root could run it too, since root ignores permission checks, but root could just use su (or sudo) which'd be much safer.
    – derobert
    Nov 1, 2018 at 20:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .