The existing answers are either incomplete or insecure. If you put your .ssh
directory into the home directory of the apache user (/var/www
) then this will also most likely serve the contents of that directory and thus expose your ssh private key to the public web. To prevent this you'd have to configure apache not to serve the .ssh
directory but none of the existing answers explains how to do this.
I'd also argue that it is still dangerous to have your .ssh
directory be a subdirectory of your publicly served www-root because even if you add a rule to your apache config, upgrading the server or doing unrelated other configurations might override this rule without you noticing.
So here is an answer that puts the key elsewhere, where it is not served by apache by default. There is not even the need to ever become the www-data
user as others are struggling with.
First, find out the home directory of our apache user, for example by looking into /etc/passwd
and looking for the www-data
user or however the apache user of your distribution is called. The home directory is likely /var/www
.
Then run (replacing /var/www
with the home directory of the apache user on your setup):
$ mkdir "$HOME/www-data.ssh"
$ ssh-keygen -q -t rsa -f "$HOME/www-data.ssh/id_rsa" -N ""
$ chown -R www-data:www-data "$HOME/www-data.ssh"
$ mkdir /var/www/.ssh
$ cat << END > /var/www/.ssh/config
> Host *
> IdentityFile $HOME/www-data.ssh/id_rsa
> END
$ chown -R www-data:www-data /var/www/.ssh
Now your www-data
user will use the ssh key in $HOME/www-data.ssh/id_rsa
for all its ssh connections and since your $HOME
is probably different from /var/www
, that directory will not be served. So even without adding any custom rules to apache, users will be able to see your .ssh/config
but they will not be able to access the private key it points to. Nevertheless, your www-data
user will know how to do it.