Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check if script is being ran with sudo or if user is not using `php`

How to make a check to find whether the script is run with sudo access or not using PHP ?

like image 889
Abul Hassan Avatar asked Oct 28 '14 10:10

Abul Hassan


2 Answers

Note: this question would probably be more appropriate on Stack Overflow, even though it refers to PHP on Unix & Linux systems (privilege elevation, permissions, etc.).

You can use PHP's POSIX functions:

  • posix_geteuid() to get the effective user ID.
  • posix_getpwuid() to get user information from an UID.

Here is a little example:

<?php
$userinfo = posix_getpwuid(posix_geteuid());
echo "This script runs with " . $userinfo["name"] . "'s privileges.";
?>

Testing...

$ php myfile.php
This script is run with myuser's privileges.
$ sudo php myfile.php
This script is run with root's privileges.

By the way, since root is always UID 0, you could just check posix_geteuid() == 0.

Now, if you want to now whether the user is using the CLI (command-line) or going through the web server, have a look at this question on Stack Overflow and the php_sapi_name() function.

Another note: I'm pretty sure that running PHP scripts as root isn't the best of ideas. You may want to think again about what permissions your script really needs.

like image 86
John WH Smith Avatar answered Oct 18 '22 05:10

John WH Smith


If it's purely about determining whether sudo is used, sudo puts a number of values in the environment of the command:

SUDO_COMMAND=/usr/bin/commandname
SUDO_USER=wurtel
SUDO_UID=1000
SUDO_GID=1001

These can be checked in php using the getenv() function. Of course, combine it with posix_geteuid() function to make sure you really do have elevated privileges as anyone can set those values in the environment.

like image 41
wurtel Avatar answered Oct 18 '22 04:10

wurtel