Search code examples
phpshellexecshell-execgnupg

GNUPG Escaping echoed data in shell_exec


I really want to go about this securely, as there is customer data involved.

I am using GNUPG via the command line because I am on shared hosting, and the PHP class is not available. So my code is as follows:

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

$gpg = '/usr/bin/gpg';
$gpgrecipient = 'email';
$mailrecp = 'email';
$plain = 'Here is the encrypted Text Here is the encrypted Text Here is the
    encrypted Text Here is the encrypted Text Here is the encrypted Text Here is the
    encrypted Text Here is the encrypted Text Here is the encrypted Text Here is the  
    encrypted Text';



$encrypted = shell_exec("echo {$plain} | {$gpg} --no-auto-check-trustdb --lock-never -e -a -r {$gpgrecipient} ");

So, how do I go about escaping $plain, while preserving data integrity?

If I just use escapeshellcmd() it tends to mess up formatting.

I am a bit leery of saving anything out to a file because it is sensitive data on shared hosting.


Solution

  • I don't know php very well, but have you considered using proc_open rather than shell_exec? It seems cleaner than invoking a shell command to echo the input and pipe it to gpg.

    But if you'd rather use proc_open, consider using printf rather than echo -n; it has better defined behavior. For example (untested):

    $encrypted = shell_exec("printf '%s' '{$plain}' | {$gpg} ...`
    

    With echo, you run the risk that the echo command (which could be either a shell built-in or the /bin/echo command) might interpret some of its arguments as something other than strings to be printed.