title: WSL2でYubikeyを使う
author: Amane Katagiri
summary: 令和最新版テクニック
date: 2024-02-09T14:48:00+09:00
category: tech
license: CC BY 4.0
og_image: images/yubikey-on-wsl2/og.png
rating: sfw
ai_summary: WSL2でYubikeyをOpenPGPスマートカードとして利用するための設定ガイドです。Windows側のgpg-agentとWSL2を連携させるため、npiperelayやsocat、wsl2-ssh-pageantといったツールを用いたソケットのリレー方法を詳しく解説しています。systemd有効環境での注意点やSSH認証への活用、自動起動スクリプトの記述例など、具体的な構築手順がまとめられています。
ai_keywords: WSL2, Yubikey, GnuPG, OpenPGP, npiperelay, wsl2-ssh-pageant, socat, Windows, SSH認証, スマートカード

/\* この記事は、[WSLでYubikeyを使う](/post/yubikey-on-wsl)の情報を[WSL2](https://learn.microsoft.com/ja-jp/windows/wsl/compare-versions)向けに書き直したものです。詳細については元の記事もお読みください。 \*/

[TOC]

# 概要

![WSLからYubikeyを使う方法について、WSL→WSLのGnuPG→socat→npiperelay→Windowsのgpg-agent→scdaemon→Yubikey、またはssh→ssh-agent→wsl-ssh-pagent→Windowsのgpg-agent→scdaemon→Yubikeyという流れで接続できることを示す図（記事では触れないが、RemoteFXを通すとリモートデスクトップの接続先からでもYubiKeyを使用できることを提示）](/images/yubikey-on-wsl2/tldr.png){width=700 height=525}

# 前提

## Yubikey

今回は[PIV](https://www.yubico.com/authentication-standards/smart-card/)ではなく、[OpenPGP](https://support.yubico.com/hc/en-us/articles/360013790259-Using-Your-YubiKey-with-OpenPGP)コンパチブルなスマートカードとして使用します。鍵のセットアップは各自で済ませてください。

## WSL

WSL2を使います。[systemdを有効にしておく](https://devblogs.microsoft.com/commandline/systemd-support-is-now-available-in-wsl/)ことをおすすめします。

# 準備

## gpg

Yubikeyをgpg-agent経由で引き渡す必要があるので、両方にインストールしてください。

### on WSL

```shell-session
amane@yakumo:~$ sudo apt update && sudo apt install -y gpg
amane@yakumo:~$ gpg --version
gpg (GnuPG) 2.2.40
```

### on Windows

[Gpg4win](https://www.gpg4win.org/get-gpg4win.html)をインストールします。選択可能なコンポーネントは入れても入れなくてもいいです。

WindowsでYubikeyが認識できることを確認してください。Windowsで認識できなければWSLでも参照できません。

```doscon
C:\Users\amane>gpgconf --reload scdaemon

C:\Users\amane>gpg --card-status
Reader ...........: Yubico YubiKey OTP FIDO CCID 0
Application ID ...: ********************************
Application type .: OpenPGP
Version ..........: 2.1
Manufacturer .....: Yubico
Serial number ....: ********************************
Name of cardholder: Amane Katagiri
Language prefs ...: ja
Salutation .......: Ms.
URL of public key : https://keybase.io/amane/pgp_keys.asc
Login data .......: amane
Signature PIN ....: 強制
Key attributes ...: rsa4096 rsa4096 rsa4096
Max. PIN lengths .: 127 127 127
PIN retry counter : 3 0 3
Signature counter : 0
Signature key ....: **** **** **** **** ****  **** **** **** **** ****
      created ....: 1970-01-01 00:00:00
Encryption key....: **** **** **** **** ****  **** **** **** **** ****
      created ....: 1970-01-01 00:00:00
Authentication key: **** **** **** **** ****  **** **** **** **** ****
      created ....: 1970-01-01 00:00:00
General key info..: [none]
```

上手くいかない場合は、 `%APPDATA%\gnupg\scdaemon.conf` に以下を追記してやり直してください:


```text
reader-port Yubico
```

後で使うので`%APPDATA%\gnupg\gpg-agent.conf`に追記してください:

```text
enable-ssh-support
enable-win32-openssh-support
enable-putty-support
```

## npiperelay

> npiperelay is a tool that allows you to access a Windows named pipe in a way that is more compatible with a variety of command-line tools.
> ["""NZSmartie/npiperelay"""](https://github.com/NZSmartie/npiperelay)

Windowsの名前付きパイプをよしなにUNIXソケットにリレーする。GnuPGが使う[libassuan](https://gnupg.org/software/libassuan/index.html)向けのサポートつき。

[npiperelay.exe](https://github.com/NZSmartie/npiperelay/releases/download/v0.1/npiperelay.exe)を`%HOMEDRIVE%%HOMEPATH%\go\bin`あたりに置いてください。

## wsl2-ssh-pageant

> I use a Yubikey to store a GPG key pair and I like to use this key pair as my SSH key too. GPG on Windows exposes a Pageant style SSH agent and I wanted a way to use this key within WSL2.
> ["""BlackReloaded/wsl2-ssh-pageant"""](https://github.com/BlackReloaded/wsl2-ssh-pageant)

PageantをよしなにUNIXソケットにリレーする。どうしてもgpg-agent経由でsshできなかったので入れました。WSL2では元記事に記載のwsl-ssh-pageantが使えなくなっていたのでこちらを使います。

[wsl2-ssh-pageant.exe](https://github.com/BlackReloaded/wsl2-ssh-pageant/releases/download/v1.4.0/wsl2-ssh-pageant.exe)も`%HOMEDRIVE%%HOMEPATH%\go\bin`あたりに置いてください。

## socat

> Multipurpose relay (SOcket CAT)
> ["""socat(1)"""](https://linux.die.net/man/1/socat)

npipereleyでよしなにしたgpg-agentのソケットを、WSL側のgpg-agentのソケットにつなぐ。

WSLでインストールしてください:

```shell-session
amane@yakumo:~$ sudo apt update && sudo apt install -y socat
amane@yakumo:~$ socat -V
socat by Gerhard Rieger and contributors - see www.dest-unreach.org
socat version 1.7.3.2 on Nov 19 2017 13:56:10
```

# 起動

## on Windows

適当にバッチファイルとして置いてください:

```bat
gpg-connect-agent reloadagent /bye > nul 2>&1
```

タスクスケジューラからVBScript経由で呼び出すと *かわいい* かもしれないです:

```vbscript
Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c C:\path\to\start-agent.bat", vbhide
```

## on WSL2

`.bashrc`などに追記してください:

```sh
WIN_USERNAME="amane"

GO_BIN_DIR="/mnt/c/Users/${WIN_USERNAME}/go/bin"
WIN_GPG_DIR="C:/Users/${WIN_USERNAME}/AppData/Local/gnupg"
WIN_HOME_DIR="/mnt/c/Users/${WIN_USERNAME}"
WSL_GPG_DIR="$(gpgconf --list-dirs socketdir)"

if ! pgrep -f 'socat.*gpg-agent.*npiperelay' >/dev/null; then
  rm -f "${WSL_GPG_DIR}/S.gpg-agent"
  setsid nohup socat \
    UNIX-LISTEN:"${WSL_GPG_DIR}/S.gpg-agent,fork" \
    EXEC:"${GO_BIN_DIR}"'/npiperelay.exe -ei -ep -s -a "'"${WIN_GPG_DIR}"'/S.gpg-agent",nofork' >/dev/null 2>&1 &
fi
export SSH_AUTH_SOCK="/tmp/wsl2-ssh-pagent.sock"
if ! pgrep -f 'socat.*wsl2-ssh-pagent.*' >/dev/null; then
  rm -f "${SSH_AUTH_SOCK}"
  setsid nohup socat \
    UNIX-LISTEN:"${SSH_AUTH_SOCK},fork" \
    EXEC:"${GO_BIN_DIR}"'/wsl2-ssh-pageant.exe' >/dev/null 2>&1 &
fi
```

<!-- WSL2でsystemdを有効にすると、pam_systemdが `$XDG_RUNTIME_DIR` を `/run/user/$UID` に設定します。gpgがこのパスを参照してソケットを使おうとするため、固定文字列ではなくgpgconfコマンドから設定を取り出しています。 -->

PIDとかを記録すれば、もっと丁寧に二重起動を回避できますね。

なお、ここまで実施しても動作しない場合、gpg-agent.socketとsocatが競合しているかもしれません。当該のsystemdサービスを停止してください。

```sh
systemctl disable --global gpg-agent.socket
```

# おしらせ

今後のWSLのアップデートで記載している手順が動作しなくなった場合は、気付き次第この記事を修正する予定です（WSL3がリリースされた場合はまた別の記事に分割すると思います）。

# 参考

* [Using a Yubikey for GPG in WSL (Windows Subsystem for Linux) on Windows 10](https://justyn.io/blog/using-a-yubikey-for-gpg-in-wsl-windows-subsystem-for-linux-on-windows-10/)
* [SSH on Windows with private key on Yubikey](https://www.antirandom.com/2020/03/ssh-on-windows-with-private-key-on-yubikey/)
* [How to use GPG with YubiKey (bonus: WSL)](https://codingnest.com/how-to-use-gpg-with-yubikey-wsl/)
* [GPG with Yubikey doesn't work on WSL2 with systemd activated · Issue #9817 · microsoft/WSL](https://github.com/microsoft/WSL/issues/9817)
