Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: changing user mid-script

by kschwab (Vicar)
on Oct 10, 2001 at 02:14 UTC ( [id://117887]=note: print w/replies, xml ) Need Help??


in reply to changing user mid-script

There is a concept of both a "real" and "effective" uid in a process. Most things that a process does are done in the context of the "effective uid". ( For example, if you open a file, it will be owned by the effective uid).

If the process is running as the root user, it can change both it's real and effective uid. The catch is, you can only change these if your "effective" uid is 0 (root).

So, yes, you can change them midstream, but your effective uid had to be '0' when you started, and you'll have to reset it back to '0' before you change it to something else. Further complicating the matter, you can't set it to '0' unless your real uid is '0'. Whee.

This means the script has to be run as root, either directly, or via setuid flags on the script. This can be dangerous. Caveat Emptor.

Items to peruse:

An example:

#!/usr/bin/perl -wT # # -T to set taint mode use strict; # # setup ENV for taint mode # delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; $ENV{PATH}="/bin:/usr/bin"; # # die unless the process is running with # an effective uid of 0 (root) # die "Must run as root" unless ($> == 0); # # explicitly set real uid to 0 (root), # so that we can switch effective uid at will # $<=0; if ($< != 0) { die "Couldn't set real uid to 0: $!\n"; } if( my $id =getpwnam("http")) { # set the effective uid to http's uid $>=$id; if ($> != $id) {die "seteuid failed: $!\n"} # run the id shell command that lists uid,euid,etc system("id"); } if( my $otherid =getpwnam("nobody")) { # reset the effective uid to 0, or you won't be able to # set it to nobody's uid $>=0; $>=$otherid; if ($> != $otherid) {die "seteuid failed: $!\n"} system("id"); }

Update: I was addressing the question rather directly. (changing uid's midway through a script). It's probably a better idea to use two different scripts, and something like sudo or super that would allow one user to run a script as another user. Setuid scripts should be a last resort.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://117887]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (7)
As of 2024-04-25 08:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found