Search code examples
encryptiongnupgshell-exec

GPG decrypts file with no content/as empty file


i am struggling with a gpg problem for a few days and cant figure out a solution by my own. i would be glad if you could help me out with the following issue:

i need to decrypt a gpg file in php. for that, i am using the following command:

cat passphrase.txt | /usr/local/bin/gpg --decrypt --passphrase-fd 0 stammdaten.txt.gpg>stammdaten.txt

the passphrase.txt contains the password for decryption
stammdaten.txt.gpg is the encrypted file
the decrypted data will be written in stammdaten.txt

when i run this command in php:


shell_exec=("cat passphrase.txt | /usr/local/bin/gpg --decrypt --passphrase-fd 0 stammdaten.txt.gpg>stammdaten.txt")


i get a zero-byte output file (stammdaten.txt) with owner=ftpadmin and group=psacln

but when i execute the same command via ssh terminal (as root), the data will be decrypted and written correctly with file owner=root and group=root.

i think, that this is a permission problem. how can i use that command in php correctly? i also tried to chown and chgrp with the ftprightson the decrypted file, but nothing seems to help.

every answer is highly appreciated. thanks!


Solution

  • finally i got it to work:

    first of all, i changed the gpg command for decryption with echoing the passphrase into stdin:

    $passphrase = utf8_decode('mypassphrase');
    $encrypted = 'fullsystempathtogpgfile.gpg';
    
    "echo '$passphrase' | /usr/local/bin/gpg -v -v --batch --passphrase-fd 0 --no-default-keyring $encrypted";
    

    before executing with shell_exec i needed to change the homedir of gpg:

    before it was set with:

    putenv("GNUPGHOME=/var/www/.gnupg");
    

    but obviously the php user (in my case "ftpadmin", found out with "whoami") has no permission to access that directory, so i copied the .gpg folder into my new created php user folder: /home/ftpadmin (with 777 perms) and changed the GNUPGHOME:

    putenv("GNUPGHOME=/home/ftpadmin/.gnupg");
    

    now i am able to decrypt the gpg files with php. maybe you could find some help for your similar issue. thanks again for every answer.