Ssh – Accessing SSH_AUTH_SOCK from another non-root user

sshssh-agentsudo

The Scenario:

I am running ssh-agent on my local PC, and all my servers/clients are setup to forward SSH agent auth. I can hop between all my machines using the ssh-agent on my local PC. That works.

I need to be able to SSH to a machine as myself (user1), change to another user named user2 (sudo -i -u user2), and then ssh to another box using the ssh-agent I have running on my local PC. Lets say I want to do something like ssh user3@machine2 (assuming that user3 has my public SSH key in their authorized_keys file).

I have sudo configured to keep the SSH_AUTH_SOCK environment variable.

All users involved (user[1-3]), are non privileged users (not root).

The Problem:

When I change to another user, even though the SSH_AUTH_SOCK variable is set correctly, (lets say its set to: /tmp/ssh-HbKVFL7799/agent.13799) user2 does not have access to the socket that was created by user1 – Which of course makes sense, otherwise user2 could hijack user1's private key and hop around as that user.

This scenario works just fine if instead of getting a shell via sudo for user2, I get a shell via sudo for root. Because naturally root has access to all the files on the machine.

The question:

Preferably using sudo, how can I change from user1 to user2, but still have access to user1's SSH_AUTH_SOCK?

Best Answer

There are two things you need to do:

  1. set the SSH_AUTH_SOCK variable so it points to the correct file
  2. allow the other user to connect to the socket (using file system permissions)

Therefore, what you could do is:

As user1, allow user2 to connect to the socket (full access to the socket and permissions to enter the directory). I hope your /tmp allows ACLs.

setfacl -m u:user2:rw $SSH_AUTH_SOCK
setfacl -m u:user2:x $(dirname $SSH_AUTH_SOCK)

Change to the other user, and export the variable correctly.

sudo -u user2 env SSH_AUTH_SOCK=$SSH_AUTH_SOCK ssh user3@machine2

If you want to open an interactive shell using sudo, you would have to export the SSH_AUTH_SOCK variable yourself after you get the shell.