If I have a server A into which I can login with my ssh key and I have the ability to "sudo su – otheruser", I lose key forwarding, because the env variables are removed and the socket is only readable by my original user. Is there a way I can bridge the key forwarding through the "sudo su – otheruser", so I can do stuff on a server B with my forwarded key (git clone and rsync in my case)?
The only way I can think of is adding my key to authorized_keys of otheruser and "ssh otheruser@localhost", but that's cumbersome to do for every user and server combination I may have.
In short:
$ sudo -HE ssh user@host
(success)
$ sudo -HE -u otheruser ssh user@host
Permission denied (publickey).
Best Answer
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 theenv_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 usingvisudo
) and set theenv_keep
option to the appropriate users. If you want this option to be set for all users, use theDefaults
line like this: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
inuser1@serverA
anduser2@serverB
, andserverA
's/etc/sudoers
file is setup as indicated above):