As you mentioned, the environment variables are removed by sudo
, for security reasons.
But fortunately sudo
is quite configurable: you can tell it precisely which environment variables you want to keep thanks to the env_keep
configuration option in /etc/sudoers
.
For agent forwarding, you need to keep the SSH_AUTH_SOCK
environment variable. To do so, simply edit your /etc/sudoers
configuration file (always using visudo
) and set the env_keep
option to the appropriate users. If you want this option to be set for all users, use the Defaults
line like this:
Defaults env_keep+=SSH_AUTH_SOCK
man sudoers
for more details.
You should now be able to do something like this (provided user1
's public key is present in ~/.ssh/authorized_keys
in user1@serverA
and user2@serverB
, and serverA
's /etc/sudoers
file is setup as indicated above):
user1@mymachine> eval `ssh-agent` # starts ssh-agent
user1@mymachine> ssh-add # add user1's key to agent (requires pwd)
user1@mymachine> ssh -A serverA # no pwd required + agent forwarding activated
user1@serverA> sudo su - user2 # sudo keeps agent forwarding active :-)
user2@serverA> ssh serverB # goto user2@serverB w/o typing pwd again...
user2@serverB> # ...because forwarding still works
Don't use a password. Generate a passphrase-less SSH key and push it to your VM.
If you already have an SSH key, you can skip this step…
Just hit Enter for the key and both passphrases:
$ ssh-keygen -t rsa -b 2048
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
Copy your keys to the target server:
$ ssh-copy-id id@server
id@server's password:
Now try logging into the machine, with ssh 'id@server'
, and check-in:
.ssh/authorized_keys
Note: If you don't have .ssh dir and authorized_keys file, you need to create it first
to make sure we haven’t added extra keys that you weren’t expecting.
Finally, check to log in…
$ ssh id@server
id@server:~$
You may also want to look into using ssh-agent
if you want to try keeping your keys protected with a passphrase.
Best Answer
It's pretty straightforward -- you just start the agent somewhere out of the way, feed it the key(s) of interest, then set the SSH_AUTH_SOCK environment variable in the environment of the sshfs process to point to the agent.