On Tue, Apr 16, 2002 at 11:30:08AM +0200, walter valenti wrote:
> Hi,
> i've got a demon i perl that start from root.
> 
> I would like that after the starting (when starts, does some operation 
> like root), it swiches like other user with low privileges (es. like 
> Apache, starts from root and swiches at www-data).
> 
> I'm trying the POSIX module, using the function: POSIX::setuid, and 
> POSIX::setgid but nothing.

You don't need the POSIX module, perl can do this on its own.

If you take a look at 'perldoc perlvar' and search for UID, you find the
following:

    ---------- snip ----------
       $REAL_USER_ID
       $UID
       $<      The real uid of this process.  (Mnemonic: it's the
               uid you came from, if you're running setuid.)
    ---------- snip ----------

What you really should change is the 'Effective User ID':

    ---------- snip ----------
       $EFFECTIVE_USER_ID
       $EUID
       $>      
               ...
               (Mnemonic: it's the uid you went to, if you're
               running setuid.)  $< and $> can be swapped only on
               machines supporting setreuid().
    ---------- snip ----------

Try the following code snippet:

    ---------- snip ----------
    #!/usr/bin/perl

    use strict;
    use warnings;
    $|++;

    use constant USER => 'nobody';
    use constant GROUP => 'nogroup';

    my $uid = getpwnam(USER);
    my $gid = getgrnam(GROUP);

    print "Started as $<:$( / $>:$)\n";
    $> = $uid;
    $) = $gid;
    print "Changed to $<:$( / $>:$)\n";

    while (1) {
        print "Still alive...\n";
        sleep 10;
    }
    ---------- snip ----------

Here's my session with the code:

    ---------- snip ----------
    nijushiho:~# ./snippet &
    [3] 5313
    nijushiho:~# Started as 0:0 105 0 / 0:0 105 0
    Changed to 0:0 105 0 / 65534:0 105 0
    Still alive...
    Still alive...
    ps -aef | grep snippet
    nobody    5313  5114  0 13:23 pts/1    00:00:00 /usr/bin/perl ./snippet
    root      5315  5114  0 13:24 pts/1    00:00:00 grep snippet
    nijushiho:~# kill %3
    nijushiho:~# 
    [3]+  Terminated              ./snippet
    nijushiho:~# 
    ---------- snip ----------

As you can see, 'snippet' ran as user 'nobody'.

Remember that you need to have appropriate permissions to switch users
(speak you need to be root).


Read Stevens' "Advanced Programming in the Unix Environment" for *all*
the information about this kind of topics.

Ask if you need to know more...

-- 
                       If we fail, we will lose the war.

Michael Lamertz                        |      +49 221 445420 / +49 171 6900 310
Nordstr. 49                            |                       [EMAIL PROTECTED]
50733 Cologne                          |                 http://www.lamertz.net
Germany                                |               http://www.perl-ronin.de 

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to