Search code examples
phpencryptionlibsodium

PHP - Encryption security concern (Am I vulnerable?)


I want to connect to ssh via PHP. I can do that easily but the problem is the integrity of the login details (username, password). When I first tried the code I stored my username and password in plain sight. I thought about encrypting those variables. By looking at other questions I found libsodium: https://github.com/jedisct1/libsodium-php

I am using their first example of encrypting a string:

$secret_key = sodium_crypto_secretbox_keygen();
$message = 'Sensitive information';

$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$encrypted_message = sodium_crypto_secretbox($message, $nonce, $secret_key);

Decryption:

$decrypted_message = sodium_crypto_secretbox_open($encrypted_message, $nonce, $secret_key);

By looking at the example you can see $encrypted_message, $secret_key, $nonce. I am inserting these variables in the database when I am encrypting the login details and then I am fetching them when needed in the decryption code.

I am also storing my database connection script (PDO) in a folder where there is a .htaccess file with the following content:

order deny,allow
deny from all
allow from 127.0.0.1

1. Is my approach safe and hack-proof?

2. If somebody breaches my database will they be able to use my users' data?

3. How effective is the .htaccess file and can it stop hackers from accessing the database connection file?


Solution

    1. Nothing is totally bulletproof. Anyway, this is far from it. It's your implementation that lacks. First you encrypt it, but then you store the encrypted message along with the secret key in a database.

    2. This is all that's required to decrypt it. So any SQL injection flaws OR server/database breaches could compromise the encrypted messages and render it useless. Don't store the private key on the server; especially not with it's intended message. It's nothing more than expensive cleartext if you do that.

    3. Don't even store the database connection file in the web root. It's trivial for an hacker to grab that way, look up LFI. You can store it outside e.g. in /var/www/ and serve your index.php from /var/www/public/.

    As noted in the comments, it's a little odd what you're doing here anyway. You'd probably be much better off using SSH keys with a pass phrase.