Logo

Forward SSH Agent Requests From WSL to Windows

Learn how to use the built-in Windows ssh-agent from inside your WSL instance

Published: 03 Oct, 2024


A while ago, I came across a post explaining how to forward SSH agent request originating from a WSL instance to the agent running in Windows.

Using a single agent is great because you don’t need to copy your SSH keys to different environments. Leave them on Windows and they’ll work everywhere.

In summary, all you need is the following in your bashrc:

# Configure ssh forwarding
export SSH_AUTH_SOCK=$HOME/.ssh/agent.sock
# need `ps -ww` to get non-truncated command for matching
# use square brackets to generate a regex match for the process we want but that doesn't match the grep command running it!
ALREADY_RUNNING=$(ps -auxww | grep -q "[n]piperelay.exe -ei -s //./pipe/openssh-ssh-agent"; echo $?)
if [[ $ALREADY_RUNNING != "0" ]]; then
    if [[ -S $SSH_AUTH_SOCK ]]; then
        # not expecting the socket to exist as the forwarding command isn't running (http://www.tldp.org/LDP/abs/html/fto.html)
        echo "removing previous socket..."
        rm $SSH_AUTH_SOCK
    fi
    echo "Starting SSH-Agent relay..."
    # setsid to force new session to keep running
    # set socat to listen on $SSH_AUTH_SOCK and forward to npiperelay which then forwards to openssh-ssh-agent on windows
    (setsid socat UNIX-LISTEN:$SSH_AUTH_SOCK,fork EXEC:"npiperelay.exe -ei -s //./pipe/openssh-ssh-agent",nofork &) >/dev/null 2>&1
fi

After installing the tools called socat and npilerelay, you’ll be able to use the agent running under Windows from WSL.

I’m making this post because I use the fish shell and needed to adapt the above script to work. Here’s what’s working for me:

set -x SSH_AUTH_SOCK $HOME/.ssh/.agent.sock
set ALREADY_RUNNING (ps -auxww | grep -q "[n]piperelay.exe -ei -s //./pipe/openssh-ssh-agent"; echo $status)
if test $ALREADY_RUNNING -ne 0
    if test -S $SSH_AUTH_SOCK
        echo "removing previous socket..."
        rm $SSH_AUTH_SOCK
    end
    echo "Starting SSH-Agent relay..."
    setsid socat UNIX-LISTEN:$SSH_AUTH_SOCK,fork EXEC:"npiperelay.exe -ei -s //./pipe/openssh-ssh-agent",nofork &>/dev/null &
en

Email me if you have any questions about this post.

Subscribe to the RSS feed to keep updated.