I recommend using sudo for privileged access to systems. I also recommend requiring keys for SSH authentication, with agent forwarding to trusted systems. The default settings in these two programs collide head-on when you become superuser via sudo and want to copy files from one server to another with scp or sftp.
If you’re using an SSH agent, your environment contains the location of your authentication socket.
# env | grep SSH
SSH_CLIENT=192.0.2.2 51502 22
SSH_CONNECTION=192.0.2.2 51502 188.8.131.52 22
When you copy files with scp(1) or sftp(1), the client checks for a SSH authentication socket. If the client doesn’t find one, and the user account doesn’t have a private key on this system, and the remote server doesn’t support password auth, the client will not be able to log in.
All as you would expect, right? But like any good firewall, sudo(8) removes all environment variables not explicitly permitted. To see what sudo(8) does to your environment, as well as all of sudo’s other settings, become root and run sudo -V.
# sudo -V
Sudo version 1.6.9p20
Sudoers path: /usr/local/etc/sudoers
Authentication methods: 'pam'
Syslog facility if syslog is being used for logging: local2
Environment variables to check for sanity:
Environment variables to remove:
Environment variables to preserve:
sudo sanity-checks some environment variables, deliberately strips others, and explicitly preserves a few.
To use agent forwarding for SSH authentication while running as root, add the SSH environment variables to sudo’s configuration. While I could restrict this by groups, I’ll make this a default setting. Call up visudo and add a new default.
Defaults env_keep += "SSH_CLIENT SSH_CONNECTION SSH_TTY SSH_AUTH_SOCK"
Exit superuser, use sudo to become superuser again, and your environment will retain your SSH environment.
While sudo can preserve any environment variables you wish, sudo strips the environment for very good reasons. Don’t retain environment variables unless you’re sure what they will do. And don’t retain easily-abused environment variables, such as LD_PRELOAD. If the superuser needs dangerous environment variables, put them in a separate configuration file and source that file after becoming superuser.