1

openssl_pkcs7_encrypt() requires the data to be encrypted to be read from a file and so unfortunately it requires sensitive data to be written to temporary file before being encrypted.

In a shared hosting environment, what steps can I take to minimise the risk of the sensitive data being read / stolen when having to momentarily write it into a temp file?

The code:

$file = tempnam(sys_get_temp_dir(), 'mail');
file_put_contents($file, $body);
$encrypted = tempnam(sys_get_temp_dir(), 'encrypted');
if (openssl_pkcs7_encrypt($file, $encrypted, "cert.pem", NULL)) {
    @unlink($file);
    $body = file_get_contents($encrypted);
    @unlink($encrypted);
} else {
    @unlink($file);
    @unlink($encrypted);
}

The few things that concern me are:

  • sys_get_temp_dir() depending on the environment / host, this can vary.
  • Would calling file_put_contents($file, ""); before the @unlink($file) make a difference?
  • I'd imagine a throw…catch around everything with the @unlink calls would also help
Prembo
  • 111
  • 3

3 Answers3

3

If you don't control the hardware, the risk is huge no matter what you do. The values could be pulled straight out of a memory dump if someone really wanted. Even if you manage to make the temp file exist for only a short time, you still have to worry about securely deleting it as a file deletion doesn't actually wipe the data, it just marks the space as available. It is, in fact, probably more dangerous to delete the file as the sectors then become available for another user to grab potentially. You pretty much have to trust the hosting provider to provide the isolation and have to make sure you securely wipe the file after you are done with it.

AJ Henderson
  • 41,816
  • 5
  • 63
  • 110
2

If you can afford having your "secure service" inside a shared hosing, I am sure that you can afford having a temporary clear text copy of it meanwhile you are ciphering it.

If you eventually need a more restricted, secure approach you will have to think about owning your hardware.

kiBytes
  • 3,450
  • 15
  • 26
2

If the attacker is presumed to be the web host, then the game is over.

Supposing your attacker is another PHP script running on the same Apache instance. Unless you are running setUID as yourself, then all virtual servers will be running as the Apache user and will be able to access each other's temporary files.

To resolve this you need to run your own instance of the PHP binary, and configure your .htaccess to use that instead of mod_php (which may not even be possible, I am not an apache expert).

Alternatively you may be able to use suPHP, mod_suid2, mod_ruid or similar.

If you really have no choice, then at the very least make your temp filenames a bit more random, using mt_rand() to generate the root.

But really, if security is a concern you should be looking for your own virtual server at the very least.

Ben
  • 3,697
  • 1
  • 18
  • 24