Encrypt file using GPG with exec() - php

I'm trying to encrypt a file using GPG through exec(). The file I want to encrypt is created before running this command.
$fesha = date("mdY");
$file_name = "FILE_$fesha.txt";
$myfile = fopen($file_name, "w");
//MySQL query
fwrite($myfile, $txt);
fclose($myfile);
$password = "*password*";
$commando = "gpg --encrypt --passphrase=\"$password\" --armor --batch --yes --trust-model always -r **email#public.key** \"$file_name\"";
echo shell_exec($commando);
echo $commando;
I run the PHP script while watching the "output" folder, the text file is created without any issues,
but the asc file is never created.
If I manually run the output from the PHP file (the actual GPG command) the encrypted file is created without any issue or error message.
I've been trying to solve this for a couple of hours.
I tried to use the class approach ($gpg = new gnupg();) but I was unable to install all the PECL modules/extensions.
Any help will be greatly appreciated.

After hours and hours of research, trial and error with more command parameters, trying with permissions on the server-side, tried to add www-data user to the admin realm, modifying permissions on /home/www-data/.gnupg and /home/mainuser/.gnupg folders...
I did something "dumb" and send this command ($commando = "gpg --gen-key";) to see if I can generate a secret key through the PHP script because I kinda figure out it had to do with permissions at this point and I was not able to log in as www-data into the terminal.
Obviously I got no interactive response, but I guess It just created an empty key or something because after I tried the original command again:
$commando = "gpg --encrypt --passphrase=\"$password\" --armor --batch --yes --trust-model always -r email#public.key \"$file_name\"";
It actually worked!
The server created the text file and the encrypted file.
So, I do not want to believe that silly thing ("gpg --gen-key") actually "solved the mystery", I want to believe it was a combination of all I did.
Just in case someone else has this issue, I found these articles really helpful.
Using GPG (GnuPG with PHP on Server.
gpg: WARNING: unsafe ownership on homedir /home/user/.gnupg
What are the correct permissions for the .gnupg enclosing folder?

I updated /etc/passwd and changed the home directory for www-data. Next I copied with recursion the /root/.gnupg to the home directory of www-data and change the owner to www-data. Seemed to work. GPG provides like a 80% smaller file size. Use 2>&1 to expose output after line return.

Related

* failed to open vchiq instance

I try to play sound from a php script to my raspberry pi 3 via the audio jack. I use in the php script the following code:
<?php
$fetch = 'wget "http://192.168.1.127/sound.mp3" -O sound.mp3 --no-check-certificate';
$play = 'omxplayer -o local sound.mp3';
echo shell_exec($fetch);
echo shell_exec("sudo chown upload sound.mp3");
echo shell_exec($play);
?>
I got the file from a local ip adress and save it to the pi. Then I play the sound via the omxplayer command. On the real shell (over SSH in Putty), the Pi will output the sound without any problems. When I try the script, I got the following error message when I use the omxplayer command.
* failed to open vchiq instance
I searched then in forums for this error. They mean that it will be something with the missing permission of the file. For that I set the whole directory to the permission level 777 and the fileowner, as you can see in the script, to upload.
Unfortunately, this didn't work. Does anyone have another solution to get an output from the pi?
Thanks for every responses.
Omxplayer is a video and audio player. Your user needs to be in the video group, even though you only want to playback audio.
Don't use the 777 mode on the /dev/vchiq because it's not secure! A better solution is to add your user to the system group called video. For example:
To add user testuser in your Linux system to the video group, use this command:
usermod -aG video testuser
Finally I found a solution for that problem, after I searched again. The problem was with a directory in the /dev. I hit the following command in the command line and it works great.
sudo chmod 777 /dev/vchiq
A lot of users have actually been brought to this question because they tried raspistill and it returned this error.
In any case, the error is usually because you forgot to add the sudo, so sudo raspistill -o output.jpg should work.

shell_exec not working when excuted from browser | ssh | scp | keygen

What I want to do is:
execute "shellUnlock.php" from browser
then "scriptUNLOCK.sh" executed from the "shellUnlock.php"
then "resultUNLOCK.log" created from the scriptUNLOCK.sh
then show "resultUNLOCK.log" in browser
Notes:
For the SSH i used keygen, so i don't have to insert any password again from my server.
I used the SCP to copy "resultUNLOCK.log" created in "da.serv.er" to my own folder.
I have try it from browser, but it shows no output at all.
The script works well when I execute from putty but from shell_exec it's not work.
And I don't have access to install anything in the server.
my "shellUnlock.php" file
$myfile = fopen("nameUSER.txt", "w") or die("Unable to open file!");
$txt = "USERNAME";
fwrite($myfile, $txt);
fclose($myfile);
shell_exec('./scriptUNLOCK.sh');
if (file_exists("resultUNLOCK.log"))
echo readfile("resultUNLOCK.log");
}else{
echo "Please Try";
}
my "scriptUNLOCK.sh" script
#!/bin/bash
HOST='user#da.serv.er'
HOME='/home/web/UNLOCK'
DIR='/somewhere/script/UNLOCK/'
cd ${HOME}
while read nameUSER
do
ssh ${HOST} <<END_SCRIPT
cd ${DIR}
unlock.sh ${nameUSER} > resultUNLOCK.log
exit
END_SCRIPT
cd ${HOME}
scp ${HOST}:${DIR}resultUNLOCK.log ${HOME}
done < nameUSER.txt
Now please help me. I'm totally confused. Thanks.
If the script works fine when running it from the command line but it doesn't when you trigger it via your webserver it has to be a permission or/and path problem.
Ensure that the apache user (either www-data, www or apache by default) has write access to the UNLOCK folder and I think it will work.
And you should probably change the name of your "HOME" variable since HOME is a fix environment variable in Linux. I don't know if this is a problem, but i would change the name nevertheless to avoid disorder.
Best way would be to make it via groups
sudo usermod -a -G www-data <apache_user>
sudo chgrp -R www-data /somewhere/script/UNLOCK/
sudo chmod -R g+w /somewhere/script/UNLOCK/
So at least the user you use to login via putty must have the rights to modify the accessibility of the directory. If not, you can either contact your system administrator or use another folder you have access on.
I hope this helps.
Kind Regards
My problem solved!
Instead using shell_exec in php, i directly execute the script using crontab.
I'm sure I can find other best solution to solve this case if I have no limited time.
But the time forces me. :D
Well at least IT WORKS!
Thanks all..!

Don't want php script to execute the shell command as apache user when it is executed through browser?

I have created a PHP script that generates some .gz files, when I execute the PHP script through command line (cli), it generate the .gz file having 'desert' as user but when the script is executed through browser it generates the .gz file with 'nobody' as user which should not happen. I want the generated file to have 'desert' user rather than 'nobody' user when the script is executed through browser.
Here is the code I have created:
$file='test';
$newFileGZipCommand = 'cat '.$file.'_new | gzip > '.$file.'.gz';
//$newFileGZipCommand = 'sudo -u desert cat '.$file.'_new | gzip > '.$file.'.gz'; // This does not work
$newFileGZipCommandExecute = shell_exec($newFileGZipCommand);
//chmod($file.'.gz',0777) or die("Unable to change file permission");
//chown($file.'.gz', 'directu') or die("Unable to change file Owner");
I tried doing changing the file permissions and owner through chmod() and chown() functions in php but it say "chown(): operation not permitted".
Any pointer to this is highly appreciated.
[Note: I cannot change the httpd.conf or any other configuration files]
Sudo normally requires an interactive shell to enter your password. That's obviously not going to happen in a PHP script. If you're sure you know what you're doing and you've got your security issues covered, try allowing the Apache user to run sudo without a password, but only for certain commands.
For example, adding the following line in your sudoers file will allow Apache to run sudo without a password, only for the gzip command.
nobody ALL=NOPASSWD: gzip
Adjust the path and add any arguments to suit your needs.
Caution:
There might still be complications due to the way PHP calls shell
commands.
Remember that it's very risky to allow the web server to
run commands as root!
Another alternative:
Write a shell script with the suid bit to make it run as root no matter who calls it.
Probably a better alternative:
Write the commands to a queue and have cron pick them up, validate them (only allow known good requests), and run them, then mark that queue complete with the date and result.
Your end-user can then click/wait for update using ajax.
Hope it helps resolve your answer.

Programmatically append to file in PHP

I am trying to programmatically append an RSA public key to the authorized_keys file through a website and haven't been able to make any solutions I found work. I have tried using PHP's file_put_contents() function but I run into a permission denied error, and I have a python script that works, but I cannot seem to get PHP to execute it with either the exec() command or shell_exec(). Here's the relevant PHP code:
if(#$_POST['action']=='submit'){
$key = $_POST['key_field'];
//file_put_contents("/home/biosproject/.ssh/authorized_keys", $key, FILE_APPEND);
$test = "/usr/bin/python savetofile.py \"".$key."\"";
$tmp = shell_exec($test);
}
I'm aware that I need to sanitize the input but the site is currently in development so I'm just testing it like this in the meantime. Right now I'm using XAMPP which runs Apache. Is there something I'm missing or could try? For the PHP exec/shell_exec, I have tried using the full pathnames for all parts of the command, but nothing has worked yet. The python script is as follows:
#!usr/bin/python
import sys
key = sys.argv[1]
with open("/home/biosproject/.ssh/authorized_keys","a") as append:
diditwork = append.write(key)
print key
As I mentioned before, this script is functional, but I can't call it from the PHP script.
EDIT:
My authorized_keys file looks like so: -rw-rw-rw- 1 biosproject www-data 1200 Apr 15 13:17 /home/biosproject/.ssh/authorized_keys
UPDATE:
I fixed the problem by bypassing permissions using a cron job that appends the necessary information from a database entry instead. Works great now!
The Python script won't help you here - it's a permissions issue with the /home/biosproject/.ssh/authorized_keys file, i.e. Apache doesn't have permission to modify it, and nor will any process it spawns, which would include your Python script.
Simplest fix would be to change the file permissions so it's writable by Apache. Assuming apache runs as group www-data, do...
sudo chgrp www-data /home/biosproject/.ssh/authorized_keys
sudo chmod g+w /home/biosproject/.ssh/authorized_keys
...although I forget if ssh complains if authorized_keys is set to g+w.
Update
It occurs to me that www-data will also need +x access to all parent directories of /home/biosproject/.ssh/authorized_keys to be able to change it, although I'm pretty sure that ssh will complain if you change the .ssh directory permissions in this way.
You'll either have to run apache with the same UID as the owner of the /home/biosproject/.ssh directory, or use a setuid script to make the changes.
Explanation about my inline code:
$text = "nice text to append :P";
// open a file handler with a+ flag that means "open file for append and if it does not exist, create it"
$fo = fopen("filename.ext", "a+");
// append $text to file handler with a \n at the end
fwrite($fo, $text . PHP_EOL);

File not found, but files are present

I'm working on a server where users should be able to run protein sequences against a database, and it uses an executable called blastall. The server generates an executable which it should then run using batch. However, it doesn't appear to be running. Here is an example of an executable is generates (cmd.sh):
#!/usr/bin/env sh
cd /var/www/dbCAN
php -q /var/www/dbCAN/tools/blast.php -e -w /var/www/dbCAN/data/blast/20121019135548
Where the crazy number at the end of that is an auto-generated job ID based on when the job was submitted. There are 2 issues, and I'm trying to solve one at a time. The first issue is that when manually executed (by me simply running ./cmd.sh), I get the following errors:
sh: 1: /var/www/dbCAN/tools/blast/bin/blastall: not found
sh: 1: /var/www/dbCAN/tools/blast/bin/blastall: not found
sh: 1: -t: not found
But this doesn't really make sense to me, as the directory specified does in fact contain blastall. It has full rwx permissions and every directory along the way has appropriate permissions.
The blast.php file in tools looks like this:
try {
do_blast($opts["w"]);
$info['status'] = 'done';
$fp = fopen("$opts['w']/info.yaml","w")
fwrite($fp, Sypc::YAMLDump($info)); fclose($fp);
}
With of course variable declarations above it, and the do_blast function looks like this (again with variables declared above it and a cd so the directories work out):
function do_blast($workdir)
{
system("/var/www/dbCAN/tools/blast/bin/blastall -d data/blast/all.seq.fa -m 9 -p blastp -i $workdir/input.faa -o $workdir/output.txt")
system("/var/www/dbCAN/tools/blast/bin/blastall -d data/blast/all.seq.fa -p blastp -i $workdir/input.faa -o $workdir/output2.txt")
}
Any idea what may be causing this issue? I thought it may be because I'm running it and it was created by apache, but rwx is allowed for all users. I can include more information if needed, but I chose not to at this point because the original person who wrote the PHP split up everything into tons of little files, so it's difficult to pinpoint where the problem is exactly. Any ideas (if not complete solutions) are very appreciated.
EDIT: Solution found. As it turns out, the blastall executable had been compiled on a different linux system. Switched to a different executable and it ran flawlessly.
Could it be an issue with relative paths in your script? See my answer here, maybe it helps:
finding a file in php that is 4 directories up
The solution was to recompile the blastall executable. It had been compiled for Redhat and I am using Ubuntu. Unfortunately I assumed the executable I was given was for my system, not the previous one.

Categories