Skip to content

Instantly share code, notes, and snippets.

Last active July 12, 2024 20:07
Show Gist options
  • Save artizirk/d09ce3570021b0f65469cb450bee5e29 to your computer and use it in GitHub Desktop.
Save artizirk/d09ce3570021b0f65469cb450bee5e29 to your computer and use it in GitHub Desktop.
OpenPGP SSH access with Yubikey and GnuPG

NB: This document describles a 'Old-School' way of using Yubikey with SSH

Modern OpenSSH has native support for FIDO Authentication. Its much simpler and should also be more stable with less moving parts. OpenSSH also now has support for signing arbitary files witch can be used as replacement of gnupg. Git also supports signing commits/tags with ssh keys.

Pros of FIDO

  • Simpler stack / less moving parts
  • Works directly with ssh, ssh-add and ssh-keygen on most computers
  • Simpler
  • Private key can never leave the FIDO device

Cons of FIDO

  • Server needs to support ecdsa-sk or ed25519-sk signatures
  • Can't import your existing SSH keys
  • Private key can never leave the FIDO device for backup purposes.
  • By default ssh-keygen generates a FIDO key that is tied to single computer (key handle is a file in .ssh/)
  • Some FIDO devices do not support resident keys where key handle is saved in the FIDO device itself (makes it harder to use same key on multible computers)
  • My NitroKey Start with Gnuk firmware does not support FIDO :(

Pros of GnuPG

  • Supports older algorithms that are more widely supported on legacy systems like RSA and normal ed25519
  • Can import existing SSH keys
  • Possible to make backups of your keys to multiple OpenPGP cards/yubikeys/print on paper
  • E-mail signing and encryption
  • Fun for hardcore nerds

Cons of GnuPG

  • Very complex
  • Bad UX
  • Hard to understand documentation
  • Breaks easily (wrong ENV variables, pcsc conflicts)
  • Fun for only hardcore nerds...

OpenPGP SSH access with Yubikey and GnuPG

Yubikey, Smart Cards, OpenSC and GnuPG are pain in the ass to get working. Those snippets here sould help alleviate pain.

Notes written here should work on

  • Ubuntu 22.04 with Gnome
  • Debian 12 with Gnome
  • Linux Mint with Cinnamon (needs different environment setup, check comments)
  • Arch Linux with Gnome (pacman instead of apt)

This is not a step by step guide Depending on your environment, some commands might change and some parts can be skipped.

I also recommend reading The Linux Foundation - Protecting code integrity with PGP document. It gives a really good overview of basic GnuPG and OpenPGP consepts

Yubikey Config

To reset and disable not used modes on Yubikey you need the ykman program

You can install it using this command

sudo apt install yubikey-manager

GnuPG usage only needs CCID mode to be enabled. FIDO mode can also be enabled for WebAuthn

# Only enable chip card interface device
ykman config mode FIDO+CCID

# Older ykman (< v4.0) uses different syntax
ykman mode FIDO+CCID

Yubikey OpenPGP applet that is used by GnuPG can be configured with

ykman openpgp

GnuPG environment setup for Ubuntu/Debian and Gnome desktop

Make sure that gnupg, pcscd and scdaemon are installed

sudo apt install gnupg pcscd scdaemon

GnuPG Smart Card stack looks something like this

Yubikey -> pcscd -> scdaemon -> gpg-agent -> gpg commandline tool and other clients

Now we have to tell scdaemon to use pcsc interface instead of the default direct connect mode.

mkdir ~/.gnupg
cat > ~/.gnupg/scdaemon.conf <<'EOF'
pcsc-driver /usr/lib/x86_64-linux-gnu/
card-timeout 1

# Always try to use yubikey as the first reader
# even when other smart card readers are connected
# Name of the reader can be found using the pcsc_scan command
# If you have problems with gpg not recognizing the Yubikey
# then make sure that the string here matches exacly pcsc_scan
# command output. Also check journalctl -f for errors.
reader-port Yubico YubiKey

Under Ubuntu is in package called libpcsclite1. dpkg -L libpcsclite1 command can show the location of the lib.

GnuPG Trust Model

Turn on ssh like trust on first use (tofu)

cat > ~/.gnupg/gpg.conf <<'EOF'
trust-model tofu+pgp

After changing gpg configuration files, it's a good idea to restart gpg-agent.

systemctl --user restart gpg-agent.service

Testing that gpg sees your Yubikey

If everything went well then running following command should show something like this

gpg --card-status 
Reader ...........: Yubico Yubikey 4 CCID 00 00
Application ID ...: D2760001240102010006054860180000
Version ..........: 2.1
Manufacturer .....: Yubico
Serial number ....: 05486018
Name of cardholder: [not set]
Language prefs ...: [not set]
Sex ..............: unspecified
URL of public key : [not set]
Login data .......: [not set]
Signature PIN ....: not forced
Key attributes ...: rsa2048 rsa2048 rsa2048
Max. PIN lengths .: 127 127 127
PIN retry counter : 3 0 3
Signature counter : 0
Signature key ....: [none]
Encryption key....: [none]
Authentication key: [none]
General key info..: [none]


Test if Yubikey is detected

pcsc-tools package contains pcsc_scan program that can be used to check that Yubikey is detected.

sudo apt install pcsc-tools

and then run


Now you should see Card inserted and removed events on your terminal when connecting and removing Yubikey.

Restart everything

Smart Card middleware

sudo systemctl restart pcscd.service


systemctl --user restart gpg-agent.service

Check the logs

Run journalctl in another terminal window and look for scdaemon log lines

journalctl -fan100

If you see sharing violation messages then something else is probably trying to use the yubikey via opensc. Check getting-estonian-id-card-and-gnupg-scdaemon-yubikey-work-together

Switch from OpenSSH ssh-agent to GnuPG as ssh-agent


First get you need to get GnuPG agent-ssh-socket path

gpgconf --list-dirs | grep ssh

That should return something like this


And then you can set that path as SSH_AUTH_SOCK environment variable

export SSH_AUTH_SOCK=/run/user/1000/gnupg/S.gpg-agent.ssh

After that ssh-add -l shoud show your Yubikey.


This only works with Gnome Display Manager (GDM) under systemd KDE, Cinnamon and other desktops that use different login program might need a different config. Check the comments for more info.


echo "Create required directories"
mkdir ~/.config/autostart
mkdir ~/.config/environment.d

echo "==> Disable Gnome-Keyring ssh component"
cp /etc/xdg/autostart/gnome-keyring-ssh.desktop ~/.config/autostart
echo "Hidden=true" >> ~/.config/autostart/gnome-keyring-ssh.desktop

echo "==> Point ssh agent socket environment variable to GnuPG"
cat > ~/.config/environment.d/99-gpg-agent_ssh.conf <<'EOF'

echo "==> Done"
echo "Restart you computer and then GnuPG will be your ssh-agent"

Getting Estonian ID card and GnuPG scdaemon Yubikey work together.

Estonian ID-card uses OpenSC project to access private keys on the smart card. OpenSC also supports Yubikey and that will create conflicts with GnuPG scdaemon.

To fix it you can just disable Yubikey in opensc.


echo "Create required directories"
mkdir ~/.config/environment.d
mkdir ~/.config/opensc

echo "==> Creating user local OpenSC configuration"
cat > ~/.config/environment.d/99-opensc.conf <<'EOF'

cat > ~/.config/opensc/config <<'EOF'
app default {
	# debug = 3;
	# debug_file = opensc-debug.txt;

	# Lenovo USB Smartcard Keyboard pinpad implementation is broken
	reader_driver pcsc {
		enable_pinpad = false

	# Only GnuPG uses Yubikey
	ignored_readers = "Yubico YubiKey"

	framework pkcs15 {
		# use_file_caching = true;

	# Force Yubikey to use openpgp applet
	card_atr 3B:F8:13:00:00:81:31:FE:15:59:75:62:69:6B:65:79:34:D4 {
		name = "Yubico Yubikey";
		driver = "openpgp";


echo "==> Done"
echo "Restart your computer and Yubikey support in OpenSC will be disabled"

To make coperation between OpenSC and scdaemon even better then you have to configure scdaemon to use shared access mode, Arch Linux wiki has a short paragraph about that here

GnuPG commands

gpg -k or gpg --list-keys - List stored public keys

gpg -K or gpg --list-private-keys - List all stored private keys, # means private key is unavailable, > means private key is on a smartcard

Generate OpenPGP keys with GnuPG

  1. Generate 2048bit RSA master key with Certify(Master) and Sign permissions, expire key after 2 years
gpg --quick-generate-key "Full Name <email@email>" rsa2048 cert,sign 2y
  1. Add a 2048bit RSA encryption subkey that expires after 2 years
gpg --quick-add-key master_key_fingerprint rsa2048 encrypt 2y

where master_key_fingerprint is a 40 char hex string shown when running gpg -K

Converting openssh private key format to pem

man page says that you can use -e option to convert private and public keys to other formats, that seems to be wrong. Instead you can use -p option to request changing the password but not actually setting the password.

cp ~/.ssh/id_rsa /tmp/id_rsa  # Make a copy of the ssh private key
ssh-keygen -p -f /tmp/id_rsa -m pem

Converting pem to OpenPGP

Monkeysphere project includes a pem2openpgp command that can be used to import ssh private keys to gnupg keyring.

sudo apt install libcrypt-openssl-bignum-perl libcrypt-openssl-rsa-perl
curl > /tmp/pem2openpgp
chmod +x /tmp/pem2openpgp
/tmp/pem2openpgp 'ssh id_rsa' < /tmp/id_rsa | gpg --import

The imported key is stored without encryption, add it with those commands:

gpg --edit-key <ssh_key_id>

and then use passwd command and type the same password as your master key


After importing you can use normal gpg --edit-key command to change parameters on this key. GnuPG 2.1 also allows you to move the imported key to be one of your subkeys for authentication.

Maybe also works

Move imported SSH key to a subkey of another master key

Move the key

  1. Get the imported key keygrip value gpg --with-keygrip -k
  2. gpg --expert --edit-key <master_key_id> where master_key_id is a 40 char hex string shown when running gpg -K
  3. type addkey
  4. select (13) Existing key
  5. Copy and Paste imported ssh key keygrip
  6. Toggle off all capabilities and enable authenticate capability and finish
  7. Set key valid time to 2 years with 2y
  8. Confirm key creation and type your master key password
  9. Type save to save and exit from edit menu

Delete old public ssh key

This key is no longer needed

gpg --expert --delete-keys <ssh_key_id>

where ssh_key_id is a 40 char hex string shown when running gpg -K

Export private keys

Before moving private keys to yubikey you must make a backup of private keys so that when you lose or break your yubikey you could move the same keys to a new yubikey.

gpg --export-secret-keys > secret_keys.asc

Exported keys are encrypted with your master password.

Its also a good idea to print your private keys on a paper because files can bitrot and become unusable after some time.

paperkey < secret_keys.asc > secret_paperkey.txt

Move your private keys to Yubikey

gpg --edit-key <master_key_id>

and then use keytocard command to move the primary key to card. Then select first sub key with key 1 and then move that to card with keytocard. Then unselect first key with command key and then select second subkey with key 2 and then do keytocard. After that save and you are done.

Cloning OpenPGP card ID with Gnuk/Nitrokey Start

Edit openpgpcard_aid array in src/openpgp-do.c to contain your target card ID and then compile and flash the resulting firmware.

Alternative option for same key on different OpenPGP cards

You can tell scdaemon to force learn the new card ID with this command gpg-connect-agent "scd serialno" "learn --force" /bye


Other Notes

scdaemon with shared access for ubuntu 18.04

What do ssb and other mean in gpg --list-keys output

sec => 'SECret key'
ssb => 'Secret SuBkey'
pub => 'PUBlic key'
sub => 'public SUBkey'

# after sec/ssb means that secret key is unavailable, maybe it was exported and then deleted

> after sec/ssb means that secret key is on a smartcard/yubikey


Copy link

xirkus commented Oct 18, 2020

Here are some updated instructions I used to get this working with MacOS/OSX:

Copy link

Thank you Arti!!!

Copy link

Official bug report on the duplicate key issue:

Copy link

Yeah, copying keys to card without actually moving them there permanently is tedious and hacky with current gnupg.

One problem that is not mentioned in the bugreport is that even if you manage to create two yubikeys with the same card then you still cant use them both on the same computer as a replacement for eachother. GnuPG will remeber the card id when it moves te key and will only accept the same card/yubikey again in the future. Workaround is to delete your gnupg home folder and import clean public keys that have no info which yubikey has the private keys, in that case gnupg can figure out that it can actually use the other yubikey.

Thats why I have a backup Nitrokey Start dongle that runs Free Software gnuk firmware and allows me to clone a another cards id. This way gnupg accepts my real gnupg card and also the backup without any problems.

Copy link

myvesta commented Mar 16, 2022

apt install commands (from this tutorial) works perfectly on Debian11 too.
I just skipped apt-add-repository ppa:yubico/stable, all packages are already in Debian11 repository.

Copy link

ykman mode FIDO+CCID causes

WARNING: The use of this command is deprecated and will be removed!
Replace with: ykman config mode FIDO+CCID

Copy link

@dominik-ba updated the docs, thanks!

Copy link

myvesta commented Mar 25, 2022

@artizirk maybe to put that tutorial is fully valid for Debian11 too?
see my previous comment.

Copy link

@myvesta right, added that and also updated some other parts of the document. Thanks for testing!

Copy link

myvesta commented Mar 25, 2022

Also to mention, maybe GUI for yubikey-pin prompting window is built with Gnome library, but it will actually works with any IDE.
I personally use LXDE, no problem here, whole tutorial is valid.

Copy link

kjkent commented Mar 13, 2023

Just wanted to drop by and say thank you; I've battled GPG/YubiKey issues across different distros for over a year, with the pcscd/gpg exclusive access issues and the like. Previously I was using pcsc-shared in scdaemon.conf; but, this seems to kill PIN caching on OpenSUSE Tumbleweed (though Arch and Fedora seem to be fine). Adding disable-ccid and pcsc-driver /usr/lib64/ (on Tumbleweed) works flawlessly. I also added card-timeout 1, but I'm unsure of its utility; see

Copy link

JazzTp commented Aug 13, 2023

Ubuntu 18.04 => Raspberry PI OS 64 bit


  • client Ubuntu 18.04
  • server Raspberry PI OS 64 bit (GitHub has clear instructions on their web site, I haven't tried this with GitHub yet).

ON THE CLIENT (Ubuntu 18.04 here), add the following line to ~/.bashrc

SSH_AUTH_SOCK="`gpgconf --list-dirs | grep ssh | sed 's/agent-ssh-socket://'`" ; export SSH_AUTH_SOCK

Now still on the client, open a new terminal window so it'll have the new environment variable value (I'd recommend to close the previously open terminal windows to avoid any confusion)

Verification, this command

here is showing:

Now in the new terminal window launch this command and put the result in the clipboard:

ssh-add -L | xclip -selection c

(or just ssh-add -L and then click&drag to select the result and ctrl-shift-c)

ON THE SERVER (here it is a Raspberry PI OS 64 bit):

Paste that, appending it to the content of the file

cat >> ~/.ssh/authorized_keys/
<enter> if necessary to go to a new line, it shouldn't be necessary
or edit with nano or whatever editor you use.

If the file was not already there and you have created it, you might want to also issue:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

I don't remember if I rebooted the Rasperry PI 4 for it to work, or restarted ssh, or nothing at all, let's say "reboot".

SET UP FINISHED, it has been working for a couple of months here (sshfs too).

Additionally, I'm disabling SSH password authentication on the server:

sudo nano /etc/ssh/ssh_config

change the line
# PasswordAuthentication yes


PasswordAuthentication no

Copy link

JazzTp commented Aug 13, 2023

EDIT: see next post below, push to github Yubikey-ssh-authenticated works from Raspberry PI OS64 up to date, OpenSSH_8.4p1, with the above mentioned line used in ~./bashrc for Ubuntu 18.04:

SSH_AUTH_SOCK="`gpgconf --list-dirs | grep ssh | sed 's/agent-ssh-socket://'`" ; export SSH_AUTH_SOCK

Let me add:

I've just tried using the same key on github, the sensor button blinks, and when I touch it I get an error:

$ git push origin master
ERROR: You're using an RSA key with SHA-1, which is no longer allowed. Please use a newer client or a different key type.
Please see for more information.

fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

If you’re running Git from the command line and using OpenSSH, make sure that you’re using OpenSSH 7.2 or newer, which you can verify with ssh -V

$ ssh -V
OpenSSH_7.6p1 Ubuntu-4ubuntu0.7, OpenSSL 1.0.2n  7 Dec 2017

I have newer than the minimum required of 7.2 on this box.
I'll search if I can generate a new SSH key with the appropriate hash algorithm instead of SHA-1 (OTOH, openpgp keys here are RSA4096, I wouldn't use elliptic curves because I've read they are more vulnerable to post-quantum attacks).

You can get detailed information about GitHub’s supported SSH algorithms and what your client presents by running ssh -vvv

(No time to dig into that right now. Well, their platform their rules, I respect that, although I'd rather only issue a warning that the user's code is not as secure as it could be by using updated tools/algorithms.)

Copy link

JazzTp commented Aug 17, 2023


The same worked in Raspberry PI OS 64bit... of course AFTER setting up so that the Yubikey works with gpg, in my case not using X11 on the Raspberry PI4 but instead accessing it via SSH console. It's not OFF-TOPIC, being a necessary condition before proceeding to set up for SSH, so here's a list of steps (Yubikey 5 NFC here):
- copied udev rules from the URL specified in the page
- sudo apt install libu2f-udev scdaemon pinentry-tty
- if folder ~/.gnupg/ is not present: gpg -k should create the folder
- if not previously done, import the public key associated with the private keys stored in the Yubikey
- edit/create file ~/.gnupg/gpg-agent.conf and put this line in it (comment out eventual other pinentry-program lines if any):
pinentry-program /usr/bin/pinentry-tty (I repeat: I'm accessing this Raspberry PI4 via SSH terminal)
- THIS SHOULD NOT BE NECESSARY [EDIT: APPARENTLY IT IS]: add the following line to ~/.bashrc
export GPG_TTY=$(tty)

And after going through the "MINIMAL SET OF ACTIONS" shared above, from this Raspberry PI OS 64 box I can run git push origin master to github and authenticate touching the sensor button on the Yubikey, without any errors.

The pub key generated with ssh-add -L is identical to the one I get on Ubuntu 18.04, and the version of ssh I have on Ubuntu 18.04 is 7.6p1 > 7.2 minimum version number required according to the previously quoted GitHub doc... it's possibly > 7.6p1 what's actually needed.

On Raspberry PI OS 64 I have:

$ ssh -V
OpenSSH_8.4p1 Debian-5+deb11u1, OpenSSL 1.1.1n  15 Mar 2022

Copy link

JazzTp commented Jan 15, 2024

ON THE CLIENT (Ubuntu 18.04 here), add the following line to ~/.bashrc

SSH_AUTH_SOCK="`gpgconf --list-dirs | grep ssh | sed 's/agent-ssh-socket://'`" ; export SSH_AUTH_SOCK

The same – added into ~/.zshrc instead of .bashrc – worked in Linux Manjaro (installed from manjaro-kde-23.1.2-240102-linux66.iso downloaded 2024-01-14 then updated online).

Of course I had to import the same public key into gpg on Manjaro and also issue gpg --card-status for gpg to start using the authentication key as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment