PHP | Executing commands | Shell_exec() | Active Directory - php

Thanks for taking your time to read about my problem, so lets get straight into it.
My ultimate (end) goal is to be able to have a web base PHP app which lets users modify active directory for users inside a network.
I have found out commands that need to be ran via Powershell to change user passwords inside an active directory.
Now here is my current setup:
There is one main server where IIS is installed and the web application sits at.
There will be several computers connected to the network which navigate to the website and execute these commands
I have tried adding the code:
$query = shell_exec('Import-Module ActiveDirectory');
$query = shell_exec('$newpwd = ConvertTo-SecureString -String "'.$safe_password.'" -AsPlainText –Force');
$query = shell_exec('Set-ADAccountPassword "'.$safe_username.'" -NewPassword $newpwd –Reset');
Now here are my questions:
1) Once a computer runs that page and has those commands executed, are the commands going to be executed in the main server? where powershell is installed and permissions are granted. If not, my whole app wont work, are there any other solutions?
2) those commands are all powershell commands not cmd.exe commands. So does shell_exec() even run those commands in powershell, or just in cmd.exe. If it only runs in cmd then this wont work, how can i make it run via powershell?
I would appreciate if you could answer and help me out here, thanks alot.

Setup the Parameters in your PowerShell like this:
Param([string]$username, [string]$password)
Then call your script like this:
shell_exec("powershell.exe " . $psscriptpath . " -username \"" . $username . "\" -password \"" . $password . "\"");

Related

Can't execute sqlplus commands in shell script created by PHP page

TL;DR:
I have a PHP page which executes a shell script containing impdp which imports dump to a new schema.
PHP file:
echo shell_exec("./DumpCreator.sh 22");
DumpCreator.sh
#!/bin/bash
echo $1
impdp U_$1/Pass DIRECTORY=dmpdir DUMPFILE=MYDMP.DMP remap_schema=PARENT:U_$1
It echos 22 but impdp doesn't execute although all permissions are given to a single user (admin).
Full
I have a PHP page which creates a shell script file and overwrites its contents as the following:
$shellFile = fopen("myfile.sh" , "w");
$field = "1";
$command = "#!/bin/bash\n"
."echo $field\n"
."sqlplus system/pass as sysdba << SQLEND\n"
."create user U_$field identified by newpass;\n"
."grant dba to U_$field;\n"
."exit;\n"
."SQLEND\n";
fwrite($shellFile, $command);
$output = shell_exec("bash myfile.sh");
echo $output;
fclose($shellFile);
contents of .sh file
#!/bin/bash
echo 1
sqlplus system/pass sysdba << SQLEND
create user U_1 identified by pass;
grant dba to U_1;
exit;
SQLEND
My problem is the part of sqlplus isn't executing.
so what is wrong with this, thanks in advance.
UPDATE
When I execute .sh file itself everything executes well (user is added and granted).
UPDATE 2
I tried doing mentioned above using php oci and it ran successfully.
Now the problem is with when user is granted permission I need to copy some dump to it using a script which I will be needing to execute using PHP.
My new .sh file
#!/bin/bash
echo $1
impdp U_$1/pass DIRECTORY=DATA_PUMP_DIR DUMPFILE=something.DMP remap_schema=something:U_$1
Even if I removed $1, it doesn't execute this part and I think it doesn't require sudo or to su to root, so what am I doing wrong ? also what permissions that could be missing in the process ?
Update 3
Executing the script directly from terminal using 'admin' account which is the one Oracle is installed on, also getting the current user in PHP shows that it's 'admin'.
So the problem is with How Can I execute any non-os related commands (anything but echo, ls .. etc) from my PHP page ?
So after searching about permissions, I found that it's possible to execute anything (root or non-root commands) by editing sudoers file which will allow any php to execute any command and that's as far as I can tell is a very poor solution.
Ref : How to call shell script from php that requires SUDO?
Make sure you have the required environment variables set.
In particular you'll probably have to set LD_LIBRARY_PATH to the location of the shared libraries that come with your Oracle installation.
The PHP code is probably hiding the error messages related with this.
Compare your environment where you normally run SQL*Plus or IMP before and after running oraenv, you will need to set at least a few of those (and probably most if not all).

PHP shell_exec() not executing -- no errors

I created this DB Copy tool for my company, and everything is completely functional locally. I rsync'ed it to our tool server and now it seems it is unable to execute the shell command I'm passing with shell_exec.
$command = "/usr/bin/mysqldump -v -u$dbUser -p$dbPass ";
$command .= "-h$sourceHost -P$sourcePort $sourceDB 2>../data/dump.log ";
$command .= "| /usr/bin/mysql -u$dbUser -p$dbPass ";
$command .= "-h$targetHost -P$targetPort $targetDB 2>../data/error.log";
$output = shell_exec($command);
I capture the stderr output of the mysql dump, because that is actually used by mysqldump to show progress (dumping this table, dumping this table etc) and I read from that file on my page to show progress.
Neither of the files specified are even being created. This makes me think there is some sort of permissions issue. However I can see that my directories all have the same permissions as others on this server for working tools. Doesn't rule it out, but I'm not sure what to assess further.
I tried changing shell_exec() to exec() and adding a variable to capture the output ( exec($command, $shellOutput) ) and $shellOutput was empty.
I echo'd the command to be run, after it is formed by the script, and was able to run that on the server with no issues.
I'm a bit at a loss here, as it's not even giving me any feedback to work with. Any ideas on what I can try?
To add context, this is a page that is being called by $.ajax to kick off this dump. After this shell command, there is an echo of what db was copied, and that is returning. So the page is being called correctly, it seems to only be the shell command itself that is simply not working.
Thanks in advance.
*Also worth noting that our directory structure is such that our www folder of our project is symlinked to the documentRoot of the server.
You can try system("ur command 2>&1");
This should work and if not output why it doesn't work.
Am sure its to do with your permissions
ls -ld directory
If thats the problem change mode chmod to your preference
Etan had it correct. It was something new to me that the files are created before anything it run (but it makes complete sense). I took the files out, and the command ran. I ended up having to give apache permission to write to the data directory in my project.
Still wrapping my head around linux permissions.
Thanks all.

Laravel exec() produce a mysql-dump empty file

I'm using exec() for execute mysql-dump but it's generating an empty file on apache, but when i use the "php artisan serve" the file is generated correctly, the output file has the same user and group in apache and in the artisan serve.
Using: Ubuntu 14.04 and Xamp 5.6.12
$dir = substr(__DIR__, 0, 24).'database/backups/';
$newBackup = Backup::create();
$command = 'mysqldump -uroot lions > '.$dir.$newBackup->getDateTimeString().'.sql';
exec($command);
Ok, I was facing the same problem with Laravel 5.6 and running windows though. Before anything, you should make sure to include the password argument (either as --password or -p), even if its empty.
$cmd =
"mysqldump -h " . env('DB_HOST') .
" -u " . env('DB_USERNAME') .
" -p\"" . env('DB_PASSWORD') . "\"" .
" --databases " . env('DB_DATABASE');
The main issue is that even though several sources note that exec waits until the process is complete there is no way to know for sure, leaving that aside, since processes could be owned by different users it'd probably be better if you created a temporary file and then flashed the contents of the output array into it rather than hoping for mysqldump to do it for you.
$output = [];
$name = "your_random_file_name.sql";
exec($cmd, $output);
$tmppath = tempnam(sys_get_temp_dir(), $name);
$handle = fopen($tmppath, "w");
fwrite($handle, implode($output, "\n"));
Finally, write the main file to your desired location, in my case I upload it directly to an Amazon S3 bucket, and close the temporary file.
Storage::disk('myS3bucket')
->putFileAs("backups", new File($tmppath), $name);
fclose($handle);
I know it seems redundant but, as I mentioned above, there is no way to know for sure.
Indeed, in a development environment, it is customary not to set a password for the database. And that's why your command does not work.
But in a production environment, you are obliged to set a password for the database.
Try in your production environment (ie with a password!), And you will see that the script works.
I don't have a solution for this problem but I do know it should be possible to do this. If I enter the following command in my terminal the mysqldump works:
mysqldump "--user=root" "--password=" dbname > ~/Desktop/export.sql
But when I use this command in my scheduler as below, I gett an empty file.
$schedule->exec("mysqldump \"--user=".env('DB_USERNAME')."\" \"--password=".env('DB_PASSWORD')."\" ".env('DB_DATABASE')." > export.sql")->everyMinute();
Maybe there is someone who knows why this doesn't work? I'm guessing it's a permission issue, but I leak experience in this.

PHP CGI | IIS | Execute Permissions

I have a PHP page which uses the shell_exec command:
$psscriptpath = "C:\inetpub\htdocs\school_panel\scripts\change.ps1";
shell_exec("powershell.exe -executionpolicy remotesigned -File " . $psscriptpath . " -username \"" . $username . "\" -password \"" . $password . "\"");
However, when i submit the page aka have the code above executed, my page just times out ( never finishes loading until the time out timer is reached and i get this error):
http://puu.sh/aXEdY/22cc87310c.png
Now i have done some research and it appears that i need to somehow set some sort of executing script permissions/rights in IIS/PHP? mabey change some php.ini config? I really am not sure.
I have already tried adding permissions for powershell for IUSER and etc. I have even set the execution policy on powershell to remotesigned. It appears i have the FastCGI and CGI module installed on IIS.
I have also tried running the script via CMD using php and it WORKS, just not in the browser.
Regards
Your solution is as simple as this:
shell_exec("powershell.exe -executionpolicy remotesigned -File {$psscriptpath} -username {$username} -password {$password} < NUL");
You do not need to surround parameters in double quotes, and in order to prevent powershell from hanging, you need to pass < NUL at the end of the line.
The < NUL will force the output from PowerShell back to PHP.

Running shell scripts as root in php?

I am trying to write a php script to add users to an LDAP. To this end I have a shell script, aptly titled "addldapuser.sh", that will take in user/screenname/password combinations and add them to the LDAP. This script works properly. We would like users to be able to enter their information on a web form, which will then invoke said script and add the user to the LDAP properly. The addldapuser script currently needs to be run as root, and while I am aware of the security concerns, they can be dealt with later. I have tried everything I can think of or find, gave everything every permission I could think of, gave everything I could root, mucked around with Apache for awhile, and now I am out of ideas.
$scrName = $_POST['screenname'];
$usrName = $_POST['username'];
$pass = $_POST['password'];
if (isset($_POST['submit']))
{
$out = nl2br(shell_exec("sudo /EasyLDAP/old_scripts/addldapuser.sh " . $usrName . " " . $scrName . " " . $pass));
}
Once again, I know this is just a terrible, terrible idea that is guaranteed to end in hackers destroying us all forever, but my boss wants me to at least make it function this way.
I do know that we should at least sanitize the input, and that will be taken care of in due time.
I recently published a project that allows PHP to obtain and interact with a real Bash shell, you can easily get a shell with root. Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$strCmd = "/EasyLDAP/old_scripts/addldapuser.sh " . $usrName . " " . $scrName . " " . $pass;
$return1 = $shell->exeCmd($strCmd);
echo $return1;// return from your script
I would recommend creation of a daemon, which will be running as a root and will communicate with a script running at a user level.
You can do very simple python rpc server (e.g. XML-RPC which is built-in) and a client as a glue, run one of them as a server and root and the other one make into a client script.
The php code would then execute the python script with the required parameters, which then can communicate with the python server script.
As a benefit, you get potential security if you do the server part well. I chose python as a language which has most of the functionality built-in and is very simple to use.
Examples:
server - http://docs.python.org/library/simplexmlrpcserver.html#simplexmlrpcserver-example
client - http://docs.python.org/library/xmlrpclib.html#example-of-client-usage
Alternatively, if you insist on using php, you can run the server process as a php daemon and connect to it via some similar RPC means.

Categories