SSH is allowing remote connections only after a local login to the server

Solution 1:

The problem is that, while you are not logged in the system, your home folder is encrypted and the file ~/.ssh/authorized_keys is inaccessible.

A simple solution is described in the section Troubleshooting of the article SSH/OpenSSH/Keys from help.ubuntu.com.

To solve this, create a folder outside your home named /etc/ssh/<username> (replace <username> with your actual username). This directory should have 755 permissions and be owned by the user. Move the authorized_keys file into it. The authorized_keys file should have 644 permissions and be owned by the user.

Then edit your /etc/ssh/sshd_config and add:

AuthorizedKeysFile    /etc/ssh/%u/authorized_keys

If you want to do that for the current user (and it is in the sudoers group) the command line could looks like:

sudo mkdir /etc/ssh/$USER
sudo mv $HOME/.ssh/authorized_keys /etc/ssh/$USER/
sudo chown -R $USER:$USER /etc/ssh/$USER
sudo chmod 755 /etc/ssh/$USER
sudo chmod 644 /etc/ssh/$USER/authorized_keys

*Where $USER and $HOME are envvars that contain the username and home directory of the current user.

Then edit your /etc/ssh/sshd_config and change the directive AuthorizedKeysFile in this way:

#AuthorizedKeysFile %h/.ssh/authorized_keys
AuthorizedKeysFile /etc/ssh/%u/authorized_keys

Restart the SSH server:

sudo systemctl restart ssh.service

That's it.


References and other approaches:

  • The article "SSH/OpenSSH/Keys" from help.ubuntu.com
  • Similar question in Ask Ubuntu
  • An answer in SuperUser
  • Bug 362427 | Public key ssh auth doesn't work with my Encrypted Home Directory
  • The article "Encrypted Home directories + SSH Key Authentication" into the Stephen's space