How to setup OpenSSH agent in WSL2

Categories:

Prerequisites

Steps

  1. Run WSL2 container (e. g. Ubuntu):
    1ubuntu.exe
  2. Make a symlink in WSL user home directory to .ssh directory from Windows:
    1ln -s "/mnt/c/Users/$WINDOWS_USERNAME/.ssh" "$HOME/.ssh"
    2chmod -R go= "$HOME/.ssh"
  3. Fetch, build and install npiperelay:
    1go get -d github.com/jstarks/npiperelay
    2GOOS=windows go build -o "$HOME/.ssh/npiperelay.exe" github.com/jstarks/npiperelay
    3chmod +x "$HOME/.ssh/npiperelay.exe"
  4. Install socat:
    1sudo apt install socat
  5. Create state directory for SSH:
    1mkdir -p "$XDG_STATE_HOME/ssh" && chmod -R go= "$XDG_STATE_HOME/ssh"
  6. Add the following to $HOME/.bashrc:
    1export SSH_AUTH_SOCK="$XDG_STATE_HOME/ssh/agent.socket"
    2ss -a | grep -q "$SSH_AUTH_SOCK"
    3if (( $? != 0 )); then
    4  rm -f "$SSH_AUTH_SOCK"
    5  ( setsid socat UNIX-LISTEN:"$SSH_AUTH_SOCK",fork,user=$USER,umask=077 \
    6  EXEC:"$HOME/.ssh/npiperelay.exe -ei -s //./pipe/openssh-ssh-agent",nofork & ) >/dev/null 2>&1
    7fi
  7. Restart WSL2 container (PowerShell or CMD):
    1wsl.exe -t Ubuntu