note 92615 deleted from function.shell-exec by danbrown
| From: | danbrown@php.net | Date: | Mon, 03 Aug 2009 17:03:12 +0000 |
| Subject: | note 92615 deleted from function.shell-exec by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-159050@lists.php.net to get a copy of this message | ||
Note Submitter: abiusx at gmail dot com
----
To create a file, edit a file which Apache or your webserver user has no access to, or doing
anything with sudo or su in shell_exec, I've reached a solution after many tries.
I had a script which automated creation of PHP templates for my framework (jframework.info) in the
administration interface there.
It would ask the user for a module, generate its path and then try to save the template in that path
. it also asked for user's Username and Password on the host operating system to automatically
fix permission if PHP can't save the files by default.
Here's the script:
<?php
$File = $_POST['file'];
$data = "my template here, what to be written in file";
if (! is_writable($File) && ($_POST['save_username'] != ""
or $_POST['save_password'] != "")) //if username or password specified
{
echo "* It seems I don't have the permissions to create the file, so
I'm gonna grant it to myself using the
credentials you provided: ";
$Username = $_POST['save_username'];
$Password = $_POST['save_password'];
# here's the tricky part :
$x = shell_exec("su $Username << __eof
$Password
__eof;
echo>>$File;
chmod 777 $File;
whoami;
");
/*
a few notes about the command above:
first of all, you need to provide the su with the password from stdin, FOLLOWED BY AN EOL, so I used
HEREDOC syntax to do so.
I created an empty file instead of changing folder permissions, and set its permissions to 777.
After everything I called a "whoami" to see if the credentials are correct. If the su
failes, this whoami would return only an EOL, otherwise it would return the $Username+EOL
Another important notice is that you should do it all inside one single shell_exec otherwise the
su-ed user won't be valid in another shell_exec
*/
$x = trim($x); //trim newline and space after whoami result
if (strtolower($x) !== strtolower($Username))
echo "<b>Invalid credentials!</b>" . BR;
else
{
$sudo = true;
}
}
if (is_writable($File))
{
$f = fopen($File, "wt");
fwrite($f, $data);
fclose($f);
echo "* $File <b>successfully created.</b>" . BR;
}
else
{
echo "* I have no permission to save this file: $File" . BR;
$sudo = false;
}
if ($sudo)
{
echo "* Now setting file permission back to safe:" . BR;
# the same magic
shell_exec("su $Username << __eof
$Password
__eof;
chmod 755 $File;
");
}
echo "* All done.";
?>