SSH agent not available after sudo or su
Why ssh-add and git say they cannot reach your agent after sudo or su on the host, what SSH_AUTH_SOCK has to do with it, and the options for each case.
Agent forwarding works through one environment variable, SSH_AUTH_SOCK, which points to a socket file that only your user can open. sudo and su change your environment, your user, or both, so one of those two links breaks.
Which error means what
Run ssh-add -l after switching user:
Could not open a connection to your authentication agent.The variableSSH_AUTH_SOCKis not set in the new environment. Usuallysudoremoved it.Error connecting to agent: Permission deniedThe variable is there, but the new user is not allowed to open your socket.Error connecting to agent: No such file or directoryThe variable points to a socket that no longer exists, often a stale value saved in a tmux or screen session from an earlier login.
Why sudo drops it
By default sudo runs commands in a minimal environment (env_reset is on). Only a short list of variables such as TERM, PATH and HOME survives, plus anything the administrator lists in env_keep. SSH_AUTH_SOCK is not on that list unless someone added it.
su - (login shell) also starts a fresh environment. Plain su keeps more of it, so the variable may be set but the socket still refuses the new user.
Why the other user cannot use it
ssh-agent creates the socket so that only the current user can open it. root can open it anyway. Any other user, for example sudo -u deploy, cannot.
What to do
- You only need the agent for one command as root. Keep the variable for that command:
sudo --preserve-env=SSH_AUTH_SOCK git pull
The site's sudoers policy decides whether you may do this; it may refuse.
- Your team does this often as root. An administrator can add the variable to
env_keepinsudoers:
Defaults env_keep += "SSH_AUTH_SOCK"
- You need it as another non-root user. The socket's permissions block that user. The clean answer is to give that user its own key or a deploy key, rather than loosening permissions on your socket.
- Avoid needing it. Run the command as yourself where you can, and use
sudoonly for the step that needs it.
Be careful with forwarded agents
Anyone who can open your agent socket can use your keys while you are connected, and root on the host always can. Forward your agent only to hosts you trust. See The agent and agent forwarding.
Related
- The agent and agent forwarding
- Jump hosts (ProxyJump)
- The ssh config file
- SSH error messages, what each one means
- SFTP with sudo: edit root-owned files with sftp -s
- SSH agent forwarding not working: Could not open a connection to your authentication agent
- ssh-add "Could not open a connection to your authentication agent": start the agent
Sources
- ssh-agent manual page (OpenSSH, SSH_AUTH_SOCK)
- ssh-add.c and authfd.c (OpenSSH source, error messages)
- sudoers manual (env_reset, env_keep)
- sudo manual (--preserve-env)
- su manual page (util-linux, --login)