色々なメモ。

私的メモ。プログラミングとか。主に自分用まとめ。

Windows上のssh-agentをWSL2から利用する

Windows上とWSL2上で重複して鍵管理したくなかったので調べた

0. 最初に参考記事

ほとんど以下のページに記載されているのそのまま。

github.com

↑は元々WSL1で同様のことを実現するためのツールらしいが(自分は使ったことないので詳しくない)、WSL2だと代わりに以下の方法でできると記載がある。

1. ssh-agentの立ち上げ(Windows

Windows上でPowerShellを管理者権限で起動し、以下を叩いてssh-agentを自動起動するように設定する

Set-Service ssh-agent -StartupType Automatic
Start-Service ssh-agent

2. npiperelayのダウンロード(Windows

以下からダウンロードして、Windows上の適当なパスに置く(あとでWSL2側から参照するので参照しやすい位置がよい)

github.com

3. socatのインストール(WSL2)

WSL2上にsocatをインストール。 Ubuntuの場合は以下:

sudo apt install socat

4. .bashrcに設定を記述(WSL2)

WSL2上で、以下を .bashrc に記載:

export SSH_AUTH_SOCK=$HOME/.ssh/agent.sock
ss -a | grep -q $SSH_AUTH_SOCK
if [ $? -ne 0 ]; then
    rm -f $SSH_AUTH_SOCK
    ( setsid socat UNIX-LISTEN:$SSH_AUTH_SOCK,fork EXEC:"/mnt/c/path/to/npiperelay.exe -ei -s //./pipe/openssh-ssh-agent",nofork & ) >/dev/null 2>&1
fi

ここで、忘れずに /mnt/c/path/to/npiperelay.exe をWSL2側から見た npiperelay.exe のパスに直すこと。

あとはターミナルを開きなおすか以下を実行して .bashrc を読み込み。

. ~/.bashrc

使い方

普通のssh-agent同様。 Windows側からでもWSL2側からでも以下で鍵を追加できる:

ssh-add /path/to/id_rsa

そうすると後はWindows側からでもWSL2側からでもssh-agentを利用してssh接続ができる。

まださっき設定して少し試したばかりなので動かなかったら追記する。

注意事項

最初のリンクから転載

SECURITY NOTICE: All the usual security caveats applicable to WSL apply. Most importantly, all interaction with the Win32 world happens with the credentials of the user who started the WSL environment. In practice, if you allow someone else to log in to your WSL environment remotely, they may be able to access the SSH keys stored in your ssh-agent. This is a fundamental feature of WSL; if you are not sure of what you're doing, do not allow remote access to your WSL environment (i.e. by starting an SSH server).

要するにWSL環境によそからアクセスできる状態であれば気を付けましょうという話っぽい。