Yubikey WSL: Agent refused operation

I recently had problems using my Yubikey GPG key to SSH from my WSL instance to a linux server. After the usual checks, it seemed like it was a client side error sign_and_send_pubkey: signing failed for RSA "/home/user/.ssh/id_rsa" from agent: agent refused operation. Most people on the internet recommend running gpg-connect-agent updatestartuptty /bye but it still did not work for me. Time to do a little more digging into the root cause.

Reading the GPG man page revealed that export GPG_TTY=$(tty) should be added to .bashrc. The archlinux wiki shed even more light on what exactly had happened. I installed xserver recently and it was causing the pinentry program to start in the wrong TTY and hence failing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# confirm that gpg in WSL can detect the yubikey 
$ gpg --card-status
Reader ...........: Yubico YubiKey OTP FIDO CCID (0001234567) 00 00
Application type .: OpenPGP
Version ..........: 2.1
Manufacturer .....: Yubico

# confirm that the GPG key is present in SSH agent as an identity
$ ssh-add -L
ssh-rsa AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
cardno:000123456789

# get GPG to use current TTY for pinentry
$ export GPG_TTY=$(tty)
$ gpg-connect-agent updatestartuptty /bye
OK
$ ssh user@192.168.0.1
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-107-generic x86_64)