Search code examples
sshssh-agent

ssh-agent denies to add root's private key with sudo user


Is there a way to add root's ssh private key in ssh-agent, with a standard sudo user?

I'm not really sure, but is this the restriction with this command?

In the ssh-add man page I found this: Identity files should not be readable by anyone but the user. Note that ssh-add ignores identity files if they are accessible by others.

Thats the output:

sudouser@myhost:/ $ ssh-agent

SSH_AUTH_SOCK=/tmp/ssh-Yppfd3Xp0Yrm/agent.2429; export SSH_AUTH_SOCK;
SSH_AGENT_PID=2430; export SSH_AGENT_PID;
echo Agent pid 2430;

sudouser@myhost:/ $ eval $(ssh-agent)
Agent pid 2435

sudouser@myhost:/ $ ssh-add /home/sudouser/.ssh/id_rsa
Enter passphrase for /home/sudouser/.ssh/id_rsa:                                                                                                                                      
Identity added: /home/sudouser/.ssh/id_rsa (/home/sudouser/.ssh/id_rsa)

Works as expected. But with root's key i get:

sudouser@myhost:/ sudo ssh-add /root/.ssh/ansible/id_rsa

or

sudouser@myhost:/ sudo sh -c 'ssh-add /root/.ssh/ansible/id_rsa'

Could not open a connection to your authentication agent.

Solution

  • sudo clears environment variables. ssh-add needs SSH_AUTH_SOCK and SSH_AGENT_PID in order to know how to speak to ssh-agent. So you must trick it by adding them back in the command:

    sudo sh -c 'export SSH_AUTH_SOCK="'"$SSH_AUTH_SOCK"'"; export SSH_AGENT_PID="'"$SSH_AGENT_PID"'"; ssh-add /path/to/roots/private/key'