WordPress SSH2 configuration

Instead of the packaged WordPress I run the version provided by WordPress. It is installed using a different userid from the userid the webserver runs as.  To enable updates from the Admin Dashboard, I enabled sftp (ssh). This is how I did it.

Using the SFTP option requires the PHP ssh module. The command below installs the PHP ssh extension. (Recent releases may have the ssh2 extension installed The distributed php-ssh2 module frequently breaks, so I use the ssh-sftp-updater-support plugin when necessary.

apt install php-ssh2

The FTP functionality includes the SFTP (ssh2) option for connectivity.  To enable this the /etc/wordpress/config.php file must be updated to include the following lines. (Use the appropriate directories for your installation.) The password is left blank as it is required, but I have not been able to get either module to work with a password-protected key.

// This value should be ssh2 not ssh
define('FS_METHOD', 'ssh2');
define('FTP_BASE', '/var/www/');
define('FTP_CONTENT_DIR', '/var/www/wp-content/');
define('FTP_PLUGIN_DIR ', '/var/www/wp-content/plugins/');
define('FTP_PUBKEY', '/etc/wordpress/.ssh/id_rsa.pub');
define('FTP_PRIKEY', '/etc/wordpress/.ssh/id_rsa');
// user that owns wordpress install - should not be root
define('FTP_USER', 'wordpress');
// password for FTP_USER username - may be empty
define('FTP_PASS', '');
// hostname:port combo for your SSH/FTP server
define('FTP_HOST', 'localhost');

The following script creates and populates the directories required for ssh to work. An ssh key is generated and granted restricted access to the user owning the distribution. The last command verifies the setup.

# Make the directories
www-data mkdir -p -m 0755 ~www-data/.ssh /etc/wordpress/.ssh
sudo chown www-data /etc/wordpress/.ssh
# Create the known hosts file
sudo ssh-keyscan -c "localhost > ~www-data/.ssh/known_hosts"
sudo chmod 444 ~www-data/.ssh/known_hosts
# Generate the key file 
sudo -u www-data ssh-keygen -b 4096 -f /etc/wordpress/.ssh/id_rsa -N changeme
# Secure the directories
sudo chown root:www-data /etc/wordpress/.ssh ~www-data/.ssh
# Authorize the key - with restricted access
echo -n 'from="127.0.0.1,::1",restrict,pty ' >> ~/.ssh/authorized_keys
sudo cat /etc/wordpress/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
# Test the configuration - should be prompted for the key's password.
sudo -u www-data ssh -i /etc/wordpress/.ssh/id_rsa $(logname)@localhost

I hope this is useful to you. As always, please don’t use any password used in the provided scripts.

My original installation used a key without a password. At the time sftp access was not stable. I have not yet done an upgrade with a password on the key.

Leave a comment

Your email address will not be published. Required fields are marked *