Did you test this code snippet it?  It won't work.  You can't use a
numeric comparison to test for stringwise equality.  (Sorry to be
nitpicky, but it matters here.)

One of the cardinal rules of defensive programming, at least in the Unix
world, is that you shouldn't check if you can do something--you should
just try to do it.  If it fails, *then* you check to see why.  Many, many
potential security problems can be avoided that way.

Now, if you want to do the check as a nicety to the user, just for the
sake of giving an error message, that's fine--though you should do
something more like

unless ($> == 0 || $< == 0) { die "You must be root" }

The use of $< and $> both will take care of the case where you're run
under sudo.  The superuser on Unix is *always* UID 0, regardless of the
username given to it.

Now, even if you *do* do this check, you still must not assume that you
have or do not have any particular authority at any point later on in the
program.  Every time you attempt to do something that requires root
authority, prepare for it to fail, check for errors, and respond
appropriately.  Otherwise it may be possible to use your program in
nefarious ways.

Trey

In a message dated Sat, 26 Oct 2002, Mark Knipfer writes:

> On 10/26/02 11:55 AM, Mark Knipfer wrote:
> > How do you check for root level access in Perl 5.6.0 in Mac OS X?
>
> After browsing and reading through part of the O'Rielly - Programming
> Perl 2nd Edition book, I came up with this routine:
>
> $login = (getpwuid($>));
> if (!$login == "root")
>       {
>               die "\nYou cannot run this Perl script as user \"$login\", must be
> ROOT!\n\n";
>       }
>
>


Reply via email to