<?xml version="1.0" encoding="windows-1252"?>
<node id="833950" title="$&lt; and setuid: quite different animals?" created="2010-04-10 01:01:07" updated="2010-04-10 01:01:07">
<type id="115">
perlquestion</type>
<author id="325183">
saintmike</author>
<data>
<field name="doctext">
Pop quiz: What's wrong with dropping privileges of a process, started as root, to "nobody", like this?

&lt;code&gt;
my $uid = getpwnam("nobody");
$&lt; = $uid;
&lt;/code&gt;

Answer: It's easy to regain root privileges afterwards by simply assigning 0 to $&lt;.
&lt;p&gt;
Why is that? Turns out that assigning a uid to $&lt; (or the effective uid $&gt; for that matter) isn't using setuid(), at least not on Linux. Instead, it uses setreuid32() which allows the unprivileged user to switch back to the "saved set-user-ID".

You can see what's going on in a perl script like

&lt;code&gt;
$&lt; = $uid;
$&gt; = $uid;

$&gt; = 0;
$&lt; = 0;
&lt;/code&gt;

by looking at the strace output:

&lt;code&gt;
$ sudo strace ./switchback 2&gt;&amp;1 | grep '^set'
setreuid32(99, -1)                      = 0
setresuid32(-1, 99, -1)                 = 0
setresuid32(-1, 0, -1)                  = 0
setreuid32(0, -1)                       = 0
&lt;/code&gt;

The last two calls successfully restore root privileges (uid and euid) while running as an unprivileged user.

&lt;p&gt;
Question: What's the best way to drop privileges, then? POSIX:setuid( $uid ) seems to work, is that the best practice?

</field>
</data>
</node>
