Guide to Using YubiKey for GPG and SSH

35
Guide to Using YubiKey for GPG and SSH
YubiKey as a SmartCard for storing GPG encryption, signing and authentication keys, which can also be used for SSH. Many of the principles in this document are applicable to other smart card devices.

Keys stored on YubiKey are non-exportable (as opposed to file-based keys that are stored on disk) and are convenient for everyday use. Instead of having to remember and enter passphrases to unlock SSH/GPG keys, YubiKey needs only a physical touch after being unlocked with a PIN. All signing and encryption operations happen on the card, rather than in OS memory.

New! drduh/Purse is a password manager which uses GPG and YubiKey.

Security Note: If you followed this guide before Jan 2021, your PUK (Pin Unblock Key) may be set to its default value of 12345678. An attacker can use this to reset your PIN and use your Yubikey. Please see the Change PUK section for details on how to change your PUK.

If you have a comment or suggestion, please open an Issue on GitHub.

  • Purchase
  • Prepare environment
  • Required software
    • Debian and Ubuntu
    • Arch
    • RHEL7
    • NixOS
    • OpenBSD
    • macOS
    • Windows
  • Entropy
  • Creating keys
    • Temporary working directory
    • Harden configuration
  • Master key
  • Sign with existing key
  • Sub-keys
    • Signing
    • Encryption
    • Authentication
    • Add extra identities
  • Verify
  • Export secret keys
  • Revocation certificate
  • Backup
  • Export public keys
  • Configure Smartcard
    • Change PIN
    • Enable KDF
    • Set information
  • Transfer keys
    • Signing
    • Encryption
    • Authentication
  • Verify card
  • Multiple YubiKeys
  • Cleanup
  • Using keys
  • Rotating keys
    • Setup environment
    • Renewing sub-keys
    • Rotating keys
  • Adding notations
  • SSH
    • Create configuration
    • Replace agents
    • Copy public key
    • (Optional) Save public key for identity file configuration
    • Connect with public key authentication
    • Import SSH keys
    • Remote machines (SSH Agent Forwarding)
      • Use ssh-agent
      • Use S.gpg-agent.ssh
      • Chained SSH Agent Forwarding
    • GitHub
    • OpenBSD
    • Windows
      • WSL
        • Use ssh-agent or use S.weasel-pegant
        • Prerequisites
        • WSL configuration
        • Remote host configuration
    • macOS
  • Remote Machines (GPG Agent Forwarding)
    • Steps for older distributions
    • Chained GPG Agent Forwarding
  • Using Multiple Keys
  • Require touch
  • Email
    • Mailvelope on macOS
    • Mutt
  • Reset
  • Recovery after reset
  • Notes
  • Troubleshooting
  • Alternatives
  • Links

All YubiKeys except the blue “security key” model are compatible with this guide. NEO models are limited to 2048-bit RSA keys. Compare YubiKeys here. Yubico have also just released a press release and blog post about supporting resident ssh keys on their Yubikeys including blue “security key 5 NFC” with OpenSSH 8.2 or later, see here for details.

To verify a YubiKey is genuine, open a browser with U2F support to https://www.yubico.com/genuine/. Insert a Yubico device, and select Verify Device to begin the process. Touch the YubiKey when prompted, and if asked, allow it to see the make and model of the device. If you see Verification complete, the device is authentic.

This website verifies YubiKey device attestation certificates signed by a set of Yubico certificate authorities, and helps mitigate supply chain attacks.

You will also need several small storage devices (microSD cards work well) for storing encrypted backups of your keys.

To create cryptographic keys, a secure environment that can be reasonably assured to be free of adversarial control is recommended. Here is a general ranking of environments most to least likely to be compromised:

  1. Daily-use operating system

  2. Virtual machine on daily-use host OS (using virt-manager, VirtualBox, or VMWare)

  3. Separate hardened Debian or OpenBSD installation which can be dual booted

  4. Live image, such as Debian Live or Tails

  5. Secure hardware/firmware (Coreboot, Intel ME removed)

  6. Dedicated air-gapped system with no networking capabilities

This guide recommends using a bootable “live” Debian Linux image to provide such an environment, however, depending on your threat model, you may want to take fewer or more steps to secure it.

To use Debian Live, download the latest image:

$ curl -LfO https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/SHA512SUMS

$ curl -LfO https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/SHA512SUMS.sign

$ curl -LfO https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/$(awk '/xfce.iso/ {print $2}' SHA512SUMS)

Verify the signature of the hashes file with GPG:

” imported
gpg: Total number processed: 1
gpg: imported: 1

$ gpg –verify SHA512SUMS.sign SHA512SUMS
gpg: Signature made Sat 09 May 2020 05:17:57 PM PDT
gpg: using RSA key DF9B9C49EAA9298432589D76DA87E80D6294BE9B
gpg: Good signature from “Debian CD signing key ” [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: DF9B 9C49 EAA9 2984 3258 9D76 DA87 E80D 6294 BE9B”>

$ gpg --verify SHA512SUMS.sign SHA512SUMS
gpg: Signature made Sat 09 May 2020 05:17:57 PM PDT
gpg:                using RSA key DF9B9C49EAA9298432589D76DA87E80D6294BE9B
gpg: Can't check signature: No public key

$ gpg --keyserver hkps://keyring.debian.org --recv DF9B9C49EAA9298432589D76DA87E80D6294BE9B
gpg: key 0xDA87E80D6294BE9B: public key "Debian CD signing key " imported
gpg: Total number processed: 1
gpg:               imported: 1

$ gpg --verify SHA512SUMS.sign SHA512SUMS
gpg: Signature made Sat 09 May 2020 05:17:57 PM PDT
gpg:                using RSA key DF9B9C49EAA9298432589D76DA87E80D6294BE9B
gpg: Good signature from "Debian CD signing key " [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: DF9B 9C49 EAA9 2984 3258  9D76 DA87 E80D 6294 BE9B

If the public key cannot be received, try changing the DNS resolver and/or use a different keyserver:

$ gpg --keyserver hkps://keyserver.ubuntu.com:443 --recv DF9B9C49EAA9298432589D76DA87E80D6294BE9B

Ensure the SHA512 hash of the live image matches the one in the signed file.

$ grep $(sha512sum debian-live-*-amd64-xfce.iso) SHA512SUMS
SHA512SUMS:799ec1fdb098caa7b60b71ed1fdb1f6390a1c6717b4314265e7042fa271c84f67fff0d0380297f60c4bcd0c1001e08623ab3d2a2ad64079d83d1795c40eb7a0a  debian-live-10.5.0-amd64-xfce.iso

See Verifying authenticity of Debian CDs for more information.

Mount a storage device and copy the image to it:

Linux

usb-storage 3-2:1.0: USB Mass Storage device detected
scsi host2: usb-storage 3-2:1.0
scsi 2:0:0:0: Direct-Access TS-RDF5 SD Transcend TS3A PQ: 0 ANSI: 6
sd 2:0:0:0: Attached scsi generic sg1 type 0
sd 2:0:0:0: [sdb] 31116288 512-byte logical blocks: (15.9 GB/14.8 GiB)
sd 2:0:0:0: [sdb] Write Protect is off
sd 2:0:0:0: [sdb] Mode Sense: 23 00 00 00
sd 2:0:0:0: [sdb] Write cache: disabled, read cache: enabled, doesn’t support DPO or FUA
sdb: sdb1 sdb2
sd 2:0:0:0: [sdb] Attached SCSI removable disk

$ sudo dd if=debian-live-10.4.0-amd64-xfce.iso of=/dev/sdb bs=4M; sync
465+1 records in
465+1 records out
1951432704 bytes (2.0 GB, 1.8 GiB) copied, 42.8543 s, 45.5 MB/s”>

$ sudo dmesg | tail
usb-storage 3-2:1.0: USB Mass Storage device detected
scsi host2: usb-storage 3-2:1.0
scsi 2:0:0:0: Direct-Access     TS-RDF5  SD  Transcend    TS3A PQ: 0 ANSI: 6
sd 2:0:0:0: Attached scsi generic sg1 type 0
sd 2:0:0:0: [sdb] 31116288 512-byte logical blocks: (15.9 GB/14.8 GiB)
sd 2:0:0:0: [sdb] Write Protect is off
sd 2:0:0:0: [sdb] Mode Sense: 23 00 00 00
sd 2:0:0:0: [sdb] Write cache: disabled, read cache: enabled, doesn't support DPO or FUA
sdb: sdb1 sdb2
sd 2:0:0:0: [sdb] Attached SCSI removable disk

$ sudo dd if=debian-live-10.4.0-amd64-xfce.iso of=/dev/sdb bs=4M; sync
465+1 records in
465+1 records out
1951432704 bytes (2.0 GB, 1.8 GiB) copied, 42.8543 s, 45.5 MB/s

OpenBSD

Shut down the computer and disconnect internal hard drives and all unnecessary peripheral devices. If being run within a VM, this part can be skipped as no such devices should be attached to the VM since the image will still be run as a “live image”.

Boot the live image and configure networking.

Note If the screen locks, unlock with user/live.

Open the terminal and install required software packages.

Debian and Ubuntu

Note Live Ubuntu images may require modification to /etc/apt/sources.list

$ sudo apt update

$ sudo apt -y upgrade

$ sudo apt -y install wget gnupg2 gnupg-agent dirmngr cryptsetup scdaemon pcscd secure-delete hopenpgp-tools yubikey-personalization

You may additionally need (particularly for Ubuntu 18.04 and 20.04):

$ sudo apt -y install libssl-dev swig libpcsclite-dev

To download a copy of this guide:

$ wget https://raw.githubusercontent.com/drduh/YubiKey-Guide/master/README.md

To install and use the ykman utility:

$ sudo apt -y install python3-pip python3-pyscard

$ pip3 install PyOpenSSL

$ pip3 install yubikey-manager


$ sudo service pcscd start

$ ~/.local/bin/ykman openpgp info

Arch

$ sudo pacman -Syu gnupg pcsclite ccid hopenpgp-tools yubikey-personalization

RHEL7

$ sudo yum install -y gnupg2 pinentry-curses pcsc-lite pcsc-lite-libs gnupg2-smime

NixOS

Generate a NixOS LiveCD image with the given config:

x86_64-linux" } : let config = { pkgs, ... }: with pkgs; { imports = [ ]; boot.kernelPackages = linuxPackages_latest; services.pcscd.enable = true; services.udev.packages = [ yubikey-personalization ]; environment.systemPackages = [ gnupg pinentry-curses pinentry-qt paperkey wget ]; programs = { ssh.startAgent = false; gnupg.agent = { enable = true; enableSSHSupport = true; }; }; }; evalNixos = configuration: import { inherit system configuration; }; in { iso = (evalNixos config).config.system.build.isoImage; }

Build the installer and copy it to a USB drive.

On NixOS, ensure that you have pinentry-program /run/current-system/sw/bin/pinentry-curses in your $GNUPGHOME/gpg-agent.conf before running any gpg commands.

OpenBSD

$ doas pkg_add gnupg pcsc-tools

macOS

Download and install Homebrew and the following packages:

$ brew install gnupg yubikey-personalization hopenpgp-tools ykman pinentry-mac

Note An additional Python package dependency may need to be installed to use ykmanpip install yubikey-manager

Windows

Download and install Gpg4Win and PuTTY.

You may also need more recent versions of yubikey-personalization and yubico-c.

Generating cryptographic keys requires high-quality randomness, measured as entropy.

To check the available entropy available on Linux:

$ cat /proc/sys/kernel/random/entropy_avail
849

Most operating systems use software-based pseudorandom number generators. On newer machines there are CPU based hardware random number generators (HRNG) or you can use a separate hardware device like the White Noise or OneRNG will increase the speed of entropy generation and possibly the quality.

From YubiKey firmware version 5.2.3 onwards – which introduces “Enhancements to OpenPGP 3.4 Support” – we can gather additional entropy from the YubiKey itself via the SmartCard interface.

YubiKey

To feed the system’s PRNG with entropy generated by the YubiKey itself, issue:

$ echo "SCD RANDOM 512" | gpg-connect-agent | sudo tee /dev/random | hexdump -C

This will seed the Linux kernel’s PRNG with additional 512 bytes retrieved from the YubiKey.

OneRNG

Install rng-tools software:

$ sudo apt -y install at rng-tools python3-gnupg openssl

If you have a hardware device other than the CPU based one, install the accompany software and point rng-tools to its /dev/ device.

OneRNG specific example:

$ sudo apt -y install python-gnupg
$ wget https://github.com/OneRNG/onerng.github.io/raw/master/sw/onerng_3.6-1_all.deb

$ sha256sum onerng_3.6-1_all.deb
a9ccf7b04ee317dbfc91518542301e2d60ebe205d38e80563f29aac7cd845ccb  onerng_3.6-1_all.deb

$ sudo dpkg -i onerng_3.6-1_all.deb

$ echo "HRNGDEVICE=/dev/ttyACM0" | sudo tee /etc/default/rng-tools

Plug in the device and restart rng-tools:

$ sudo atd

$ sudo service rng-tools restart

Test by emptying /dev/random – the light on the device will dim briefly:

After a few seconds, verify the available entropy pool is quickly re-seeded:
$ cat /proc/sys/kernel/random/entropy_avail
3049

An entropy pool value greater than 2000 is sufficient.

Temporary working directory

Create a temporary directory which will be cleared on reboot and set it as the GnuPG directory:

$ export GNUPGHOME=$(mktemp -d -t gnupg_$(date +%Y%m%d%H%M)_XXX)

Otherwise, to preserve the working environment, set the GnuPG directory to your home folder:

$ export GNUPGHOME=~/gnupg-workspace

Harden configuration

Create a hardened configuration in the temporary working directory with the following options:

$ wget -O $GNUPGHOME/gpg.conf https://raw.githubusercontent.com/drduh/config/master/gpg.conf

$ grep -ve "^#" $GNUPGHOME/gpg.conf
personal-cipher-preferences AES256 AES192 AES
personal-digest-preferences SHA512 SHA384 SHA256
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
cert-digest-algo SHA512
s2k-digest-algo SHA512
s2k-cipher-algo AES256
charset utf-8
fixed-list-mode
no-comments
no-emit-version
keyid-format 0xlong
list-options show-uid-validity
verify-options show-uid-validity
with-fingerprint
require-cross-certification
no-symkey-cache
use-agent
throw-keyids

Disable networking for the remainder of the setup.

The first key to generate is the master key. It will be used for certification only: to issue sub-keys that are used for encryption, signing and authentication.

Important The master key should be kept offline at all times and only accessed to revoke or issue new sub-keys. Keys can also be generated on the YubiKey itself to ensure no other copies exist.

You’ll be prompted to enter and verify a passphrase – keep it handy as you’ll need it multiple times later.

Generate a strong passphrase which could be written down in a secure place or memorized:

$ gpg --gen-random --armor 0 24
ydOmByxmDe63u7gqx2XI9eDgpvJwibNH

Use upper case letters for improved readability if they are written down:

$ tr -dc '[:upper:]' < /dev/urandom | fold -w 20 | head -n1
BSSYMUGGTJQVWZZWOPJG

Important Save this credential in a permanent, secure place as it will be needed to issue new sub-keys after expiration, and to provision additional YubiKeys.

Tip On Linux or OpenBSD, select the password using the mouse or by double-clicking on it to copy to clipboard. Paste using the middle mouse button or ShiftInsert.

Generate a new key with GPG, selecting (8) RSA (set your own capabilities), Certify capability only and 4096 bit key size.

Do not set the master key to expire – see Note #3.

Input any name and email address:

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.

gpg: /tmp.FLZC0xcM/trustdb.gpg: trustdb created
gpg: key 0xFF3E7D88647EBCDB marked as ultimately trusted
gpg: directory ‘/tmp.FLZC0xcM/openpgp-revocs.d’ created
gpg: revocation certificate stored as ‘/tmp.FLZC0xcM/openpgp-revocs.d/011CE16BD45B27A55BA8776DFF3E7D88647EBCDB.rev’
public and secret key created and signed.

pub rsa4096/0xFF3E7D88647EBCDB 2017-10-09 [C]
Key fingerprint = 011C E16B D45B 27A5 5BA8 776D FF3E 7D88 647E BCDB
uid Dr Duh “>

GnuPG needs to construct a user ID to identify your key.

Real name: Dr Duh
Email address: doc@duh.to
Comment: [Optional - leave blank]
You selected this USER-ID:
    "Dr Duh "

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.

gpg: /tmp.FLZC0xcM/trustdb.gpg: trustdb created
gpg: key 0xFF3E7D88647EBCDB marked as ultimately trusted
gpg: directory '/tmp.FLZC0xcM/openpgp-revocs.d' created
gpg: revocation certificate stored as '/tmp.FLZC0xcM/openpgp-revocs.d/011CE16BD45B27A55BA8776DFF3E7D88647EBCDB.rev'
public and secret key created and signed.

pub   rsa4096/0xFF3E7D88647EBCDB 2017-10-09 [C]
      Key fingerprint = 011C E16B D45B 27A5 5BA8  776D FF3E 7D88 647E BCDB
uid                              Dr Duh 

Export the key ID as a variable (KEYID) for use later:

$ export KEYID=0xFF3E7D88647EBCDB

(Optional) If you already have a PGP key, you may want to sign the new key with the old one to prove that the new key is controlled by you.

Export your existing key to move it to the working keyring:

$ gpg --export-secret-keys --armor --output /tmp/new.sec

Then sign the new key:

$ gpg  --default-key $OLDKEY --sign-key $KEYID

Edit the master key to add sub-keys:

Use 4096-bit RSA keys.

Use a 1 year expiration for sub-keys – they can be renewed using the offline master key. See rotating keys.

Signing

Create a signing key by selecting addkey then (4) RSA (sign only):

" 4096-bit RSA key, ID 0xFF3E7D88647EBCDB, created 2016-05-24 Please select what kind of key you want: (3) DSA (sign only) (4) RSA (sign only) (5) Elgamal (encrypt only) (6) RSA (encrypt only) (7) DSA (set your own capabilities) (8) RSA (set your own capabilities) Your selection? 4 RSA keys may be between 1024 and 4096 bits long. What keysize do you want? (2048) 4096 Requested keysize is 4096 bits Please specify how long the key should be valid. 0 = key does not expire = key expires in n days w = key expires in n weeks m = key expires in n months y = key expires in n years Key is valid for? (0) 1y Key expires at Mon 10 Sep 2018 00:00:00 PM UTC Is this correct? (y/N) y Really create? (y/N) y We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy. sec rsa4096/0xFF3E7D88647EBCDB created: 2017-10-09 expires: never usage: C trust: ultimate validity: ultimate ssb rsa4096/0xBECFA3C1AE191D15 created: 2017-10-09 expires: 2018-10-09 usage: S [ultimate] (1). Dr Duh

Encryption

Next, create an encryption key by selecting (6) RSA (encrypt only):

Authentication

Finally, create an authentication key.

GPG doesn’t provide an authenticate-only key type, so select (8) RSA (set your own capabilities) and toggle the required capabilities until the only allowed action is Authenticate:

Finish by saving the keys.

Add extra identities

(Optional) To add additional email addresses or identities, use adduid:

" sec rsa4096/0xFF3E7D88647EBCDB created: 2017-10-09 expires: never usage: C trust: ultimate validity: ultimate ssb rsa4096/0xBECFA3C1AE191D15 created: 2017-10-09 expires: never usage: S ssb rsa4096/0x5912A795E90DD2CF created: 2017-10-09 expires: never usage: E ssb rsa4096/0x3F29127E79649A3D created: 2017-10-09 expires: never usage: A [ultimate] (1). Dr Duh [ unknown] (2). Dr Duh gpg> trust sec rsa4096/0xFF3E7D88647EBCDB created: 2017-10-09 expires: never usage: C trust: ultimate validity: ultimate ssb rsa4096/0xBECFA3C1AE191D15 created: 2017-10-09 expires: never usage: S ssb rsa4096/0x5912A795E90DD2CF created: 2017-10-09 expires: never usage: E ssb rsa4096/0x3F29127E79649A3D created: 2017-10-09 expires: never usage: A [ultimate] (1). Dr Duh [ unknown] (2). Dr Duh Please decide how far you trust this user to correctly verify other users' keys (by looking at passports, checking fingerprints from different sources, etc.) 1 = I don't know or won't say 2 = I do NOT trust 3 = I trust marginally 4 = I trust fully 5 = I trust ultimately m = back to the main menu Your decision? 5 Do you really want to set this key to ultimate trust? (y/N) y sec rsa4096/0xFF3E7D88647EBCDB created: 2017-10-09 expires: never usage: C trust: ultimate validity: ultimate ssb rsa4096/0xBECFA3C1AE191D15 created: 2017-10-09 expires: never usage: S ssb rsa4096/0x5912A795E90DD2CF created: 2017-10-09 expires: never usage: E ssb rsa4096/0x3F29127E79649A3D created: 2017-10-09 expires: never usage: A [ultimate] (1). Dr Duh [ unknown] (2). Dr Duh gpg> uid 1 sec rsa4096/0xFF3E7D88647EBCDB created: 2017-10-09 expires: never usage: C trust: ultimate validity: ultimate ssb rsa4096/0xBECFA3C1AE191D15 created: 2017-10-09 expires: never usage: S ssb rsa4096/0x5912A795E90DD2CF created: 2017-10-09 expires: never usage: E ssb rsa4096/0x3F29127E79649A3D created: 2017-10-09 expires: never usage: A [ultimate] (1)* Dr Duh [ unknown] (2). Dr Duh gpg> primary sec rsa4096/0xFF3E7D88647EBCDB created: 2017-10-09 expires: never usage: C trust: ultimate validity: ultimate ssb rsa4096/0xBECFA3C1AE191D15 created: 2017-10-09 expires: never usage: S ssb rsa4096/0x5912A795E90DD2CF created: 2017-10-09 expires: never usage: E ssb rsa4096/0x3F29127E79649A3D created: 2017-10-09 expires: never usage: A [ultimate] (1)* Dr Duh [ unknown] (2) Dr Duh gpg> save

By default, the last identity added will be the primary user ID – use primary to change that.

List the generated secret keys and verify the output:

Add any additional identities or email addresses you wish to associate using the adduid command.

Tip Verify with a OpenPGP key best practice checker:

$ gpg --export $KEYID | hokey lint

The output will display any problems with your key in red text. If everything is green, your key passes each of the tests. If it is red, your key has failed one of the tests.

hokey may warn (orange text) about cross certification for the authentication key. GPG’s Signing Subkey Cross-Certification documentation has more detail on cross certification, and gpg v2.2.1 notes “subkey does not sign and so does not need to be cross-certified”. hokey may also indicate a problem (red text) with Key expiration times: [] on the primary key (see Note #3 about not setting an expiry for the primary key).

The master key and sub-keys will be encrypted with your passphrase when exported.

Save a copy of your keys:

On Windows, note that using any extension other than .gpg or attempting IO redirection to a file will garble the secret key, making it impossible to import it again at a later date:
$ gpg -o pathtodirmastersub.gpg --armor --export-secret-keys $KEYID

$ gpg -o pathtodirsub.gpg --armor --export-secret-subkeys $KEYID

Although we will backup and store the master key in a safe place, it is best practice to never rule out the possibility of losing it or having the backup fail. Without the master key, it will be impossible to renew or rotate subkeys or generate a revocation certificate, the PGP identity will be useless.

Even worse, we cannot advertise this fact in any way to those that are using our keys. It is reasonable to assume this will occur at some point and the only remaining way to deprecate orphaned keys is a revocation certificate.

To create the revocation certificate:

$ gpg --output $GNUPGHOME/revoke.asc --gen-revoke $KEYID

The revoke.asc certificate file should be stored (or printed) in a (secondary) place that allows retrieval in case the main backup fails.

Once keys are moved to YubiKey, they cannot be moved again! Create an encrypted backup of the keyring and consider using a paper copy of the keys as an additional backup measure.

Tip The ext2 filesystem (without encryption) can be mounted on both Linux and OpenBSD. Consider using a FAT32/NTFS filesystem for MacOS/Windows compatibility instead.

Linux

Attach another external storage device and check its label:

$ sudo dmesg | tail
mmc0: new high speed SDHC card at address a001
mmcblk0: mmc0:a001 SS16G 14.8 GiB

$ sudo fdisk -l /dev/mmcblk0
Disk /dev/mmcblk0: 14.9 GiB, 15931539456 bytes, 31116288 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Write it with random data to prepare for encryption:

$ sudo dd if=/dev/urandom of=/dev/mmcblk0 bs=4M status=progress

Erase and create a new partition table:

$ sudo fdisk /dev/mmcblk0

Welcome to fdisk (util-linux 2.33.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0x3c1ad14a.

Command (m for help): g
Created a new GPT disklabel (GUID: 4E7495FD-85A3-3E48-97FC-2DD8D41516C3).

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

Create a new partition with a 25 Megabyte size:

$ sudo fdisk /dev/mmcblk0

Welcome to fdisk (util-linux 2.33.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-31116287, default 2048):
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-31116287, default 31116287): +25M

Created a new partition 1 of type 'Linux' and of size 25 MiB.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

Use LUKS to encrypt the new partition:

$ sudo cryptsetup luksFormat /dev/mmcblk0p1

WARNING!
========
This will overwrite data on /dev/mmcblk0p1 irrevocably.

Are you sure? (Type uppercase yes): YES
Enter passphrase for /dev/mmcblk0p1:
Verify passphrase:

Mount the partition:

$ sudo cryptsetup luksOpen /dev/mmcblk0p1 secret
Enter passphrase for /dev/mmcblk0p1:

Create a filesystem:

group tables: done
Writing inode tables: done
Writing superblocks and filesystem accounting information: done”>
$ sudo mkfs.ext2 /dev/mapper/secret -L gpg-$(date +%F)
Creating filesystem with 9216 1k blocks and 2304 inodes
Superblock backups stored on blocks:
        8193

Allocating group tables: done
Writing inode tables: done
Writing superblocks and filesystem accounting information: done

Mount the filesystem and copy the temporary directory with the keyring:

$ sudo mkdir /mnt/encrypted-storage

$ sudo mount /dev/mapper/secret /mnt/encrypted-storage

$ sudo cp -avi $GNUPGHOME /mnt/encrypted-storage/

Optional Backup the OneRNG package:

$ sudo cp onerng_3.6-1_all.deb /mnt/encrypted-storage/

Keep the backup mounted if you plan on setting up two or more keys as keytocard will delete the local copy on save.

Unmount, close and disconnect the encrypted volume:

$ sudo umount /mnt/encrypted-storage/

$ sudo cryptsetup luksClose secret

OpenBSD

Attach a USB disk and determine its label:

Print the existing partitions to make sure it’s the right device:

Initialize the disk by creating an a partition with FS type RAID and size of 25 Megabytes:

Encrypt with bioctl:
$ doas bioctl -c C -l sd2a softraid0
New passphrase:
Re-type passphrase:
softraid0: CRYPTO volume attached as sd3

Create an i partition on the new crypto volume and the filesystem:

Mount the filesystem and copy the temporary directory with the keyring:
$ doas mkdir /mnt/encrypted-storage

$ doas mount /dev/sd3i /mnt/encrypted-storage

$ doas cp -avi $GNUPGHOME /mnt/encrypted-storage

Keep the backup mounted if you plan on setting up two or more keys as keytocard will delete the local copy on save.

Otherwise, unmount and disconnect the encrypted volume:

$ doas umount /mnt/encrypted-storage

$ doas bioctl -d sd3

See OpenBSD FAQ#14 for more information.

Important Without the public key, you will not be able to use GPG to encrypt, decrypt, nor sign messages. However, you will still be able to use YubiKey for SSH authentication.

Create another partition on the removable storage device to store the public key, or reconnect networking and upload to a key server.

Linux

$ sudo fdisk /dev/mmcblk0

Command (m for help): n
Partition type
   p   primary (1 primary, 0 extended, 3 free)
   e   extended (container for logical partitions)
Select (default p):
Partition number (2-4, default 2):
First sector (22528-31116287, default 22528):
Last sector, +sectors or +size{K,M,G,T,P} (22528-31116287, default 31116287): +25M

Created a new partition 2 of type 'Linux' and of size 25 MiB.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

$ sudo mkfs.ext2 /dev/mmcblk0p2
Creating filesystem with 10240 1k blocks and 2560 inodes
Superblock backups stored on blocks:
        8193

Allocating group tables: done
Writing inode tables: done
Writing superblocks and filesystem accounting information: done

$ sudo mkdir /mnt/public

$ sudo mount /dev/mmcblk0p2 /mnt/public/

$ gpg --armor --export $KEYID | sudo tee /mnt/public/gpg-$KEYID-$(date +%F).asc

OpenBSD

Windows
$ gpg -o pathtodirpubkey.gpg --armor --export $KEYID

Keyserver

(Optional) Upload the public key to a public keyserver:

$ gpg --send-key $KEYID

$ gpg --keyserver pgp.mit.edu --send-key $KEYID

$ gpg --keyserver keys.gnupg.net --send-key $KEYID

$ gpg --keyserver hkps://keyserver.ubuntu.com:443 --send-key $KEYID

After some time, the public key will propagate to other servers.

Plug in a YubiKey and use GPG to configure it as a smartcard:

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
KDF setting ……: off
Signature key ….: [none]
Encryption key….: [none]
Authentication key: [none]
General key info..: [none]”>
$ gpg --card-edit
Reader ...........: Yubico Yubikey 4 OTP U2F CCID
Application ID ...: D2760001240102010006055532110000
Version ..........: 3.4
Manufacturer .....: Yubico
Serial number ....: 05553211
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
KDF setting ......: off
Signature key ....: [none]
Encryption key....: [none]
Authentication key: [none]
General key info..: [none]

Note If the card is locked, see Reset.

Windows

Use the YubiKey Manager application (note, this is not the similarly named older YubiKey NEO Manager) to enable CCID functionality.

Enable KDF

Key Derived Function (KDF) enables YubiKey to store the hash of PIN, preventing the PIN from being passed as plain text.

Change PIN

The GPG interface is separate from other modules on a Yubikey such as the PIV interface. The GPG interface has its own PIN, Admin PIN, and Reset Code – these should be changed from default values!

Entering the user PIN incorrectly three times will cause the PIN to become blocked; it can be unblocked with either the Admin PIN or Reset Code.

Entering the Admin PIN or Reset Code incorrectly three times destroys all GPG data on the card. The Yubikey will have to be reconfigured.

Name Default Value Use
PIN 123456 decrypt and authenticate (SSH)
Admin PIN 12345678 reset PIN, change Reset Code, add keys and owner information
Reset code None reset PIN (more information)

Values are valid up to 127 ASCII characters and must be at least 6 (PIN) or 8 (Admin PIN, Reset Code) characters. See the GnuPG documentation on Managing PINs for details.

To update the GPG PINs on the Yubikey:

The number of retry attempts can be changed with the following command, documented here:
ykman openpgp access set-retries 5 5 5

Set information

Some fields are optional.

login
Login data (account name): doc@duh.to

gpg/card> list

Application ID …: D2760001240102010006055532110000
Version ……….: 3.4
Manufacturer …..: unknown
Serial number ….: 05553211
Name of cardholder: Dr Duh
Language prefs …: en
Sex …………..: unspecified
URL of public key : [not set]
Login data …….: doc@duh.to
Private DO 4 …..: [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
KDF setting ……: on
Signature key ….: [none]
Encryption key….: [none]
Authentication key: [none]
General key info..: [none]

gpg/card> quit”>

gpg/card> name
Cardholder's surname: Duh
Cardholder's given name: Dr

gpg/card> lang
Language preferences: en

gpg/card> login
Login data (account name): doc@duh.to

gpg/card> list

Application ID ...: D2760001240102010006055532110000
Version ..........: 3.4
Manufacturer .....: unknown
Serial number ....: 05553211
Name of cardholder: Dr Duh
Language prefs ...: en
Sex ..............: unspecified
URL of public key : [not set]
Login data .......: doc@duh.to
Private DO 4 .....: [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
KDF setting ......: on
Signature key ....: [none]
Encryption key....: [none]
Authentication key: [none]
General key info..: [none]

gpg/card> quit

Important Transferring keys to YubiKey using keytocard is a destructive, one-way operation only. Make sure you’ve made a backup before proceeding: keytocard converts the local, on-disk key into a stub, which means the on-disk copy is no longer usable to transfer to subsequent security key devices or mint additional keys.

Previous GPG versions required the toggle command before selecting keys. The currently selected key(s) are indicated with an *. When moving keys only one key should be selected at a time.

Signing

You will be prompted for the master key passphrase and Admin PIN.

Select and transfer the signature key.

" 4096-bit RSA key, ID 0xBECFA3C1AE191D15, created 2016-05-24

Encryption

Type key 1 again to de-select and key 2 to select the next key:

Authentication

Type key 2 again to deselect and key 3 to select the last key:

Save and quit:

Verify the sub-keys have been moved to YubiKey as indicated by ssb>:

To provision additional security keys, restore the master key backup and repeat the Configure Smartcard procedure.
Switching between two or more Yubikeys.

When you add a GPG key to a Yubikey using the keytocard command, GPG deletes the key from your keyring and adds a stub pointing to that exact Yubikey (the stub identifies the GPG KeyID and the Yubikey’s serial number).

However, when you do this same operation for a second Yubikey, the stub in your keyring is overwritten by the keytocard operation and now the stub points to your second Yubikey. Adding more repeats this overwriting operation.

In other words, the stub will point ONLY to the LAST Yubikey written to.

When using GPG key operations with the GPG key you placed onto the Yubikeys, GPG will request a specific Yubikey asking that you insert a Yubikey with a given serial number (referenced by the stub). GPG will not recognise another Yubikey with a different serial number without manual intervention.

You can force GPG to scan the card and re-create the stubs to point to another Yubikey.

Having created two (or more Yubikeys) with the same GPG key (as described above) where the stubs are pointing to the second Yubikey:

Insert the first Yubikey (which has a different serial numnber) and run the following command:

$  gpg-connect-agent "scd serialno" "learn --force" /bye

GPG will then scan your first Yubikey for GPG keys and recreate the stubs to point to the GPG keyID and Yubikey Serial number of this first Yubikey.

To return to using the second Yubikey just repeat (insert other Yubikey and re-run command).

Obviously this command is not easy to remember so it is recommended to either create a script or a shell alias to make this more user friendly.

Ensure you have:

  • Saved encryption, signing and authentication sub-keys to YubiKey (gpg -K should show ssb> for sub-keys).
  • Saved the YubiKey user and admin PINs which you changed from defaults.
  • Saved the password to the GPG master key in a permanent location.
  • Saved a copy of the master key, sub-keys and revocation certificate on an encrypted volume, to be stored offline.
  • Saved the password to that encrypted volume in a separate location.
  • Saved a copy of the public key somewhere easily accessible later.

Reboot or securely delete $GNUPGHOME and remove the secret keys from the GPG keyring:

$ sudo srm -r $GNUPGHOME || sudo rm -rf $GNUPGHOME

$ gpg --delete-secret-key $KEYID

$ unset GNUPGHOME

Important Make sure you have securely erased all generated keys and revocation certificates if an ephemeral enviroment was not used!

Download drduh/config/gpg.conf:

$ cd ~/.gnupg ; wget https://raw.githubusercontent.com/drduh/config/master/gpg.conf

$ chmod 600 gpg.conf

Install the required packages and mount the non-encrypted volume created earlier:

Linux

$ sudo apt update && sudo apt install -y gnupg2 gnupg-agent gnupg-curl scdaemon pcscd

$ sudo mount /dev/mmcblk0p2 /mnt

OpenBSD

$ doas pkg_add gnupg pcsc-tools

$ doas mount /dev/sd2b /mnt

Import the public key file:

” imported
gpg: Total number processed: 1
gpg: imported: 1″>
$ gpg --import /mnt/gpg-0x*.asc
gpg: key 0xFF3E7D88647EBCDB: public key "Dr Duh " imported
gpg: Total number processed: 1
gpg:               imported: 1

Or download the public key from a keyserver:

server hkps.pool.sks-keyservers.net
[…]
gpg: key 0xFF3E7D88647EBCDB: public key “Dr Duh ” imported
gpg: Total number processed: 1
gpg: imported: 1″>
$ gpg --recv $KEYID
gpg: requesting key 0xFF3E7D88647EBCDB from hkps server hkps.pool.sks-keyservers.net
[...]
gpg: key 0xFF3E7D88647EBCDB: public key "Dr Duh " imported
gpg: Total number processed: 1
gpg:               imported: 1

Edit the master key to assign it ultimate trust by selecting trust and 5:

Remove and re-insert YubiKey and check the status:
sec# indicates the master key is not available (as it should be stored encrypted offline).

Note If you see General key info..: [none] in the output instead – go back and import the public key using the previous step.

Encrypt a message to your own key (useful for storing password credentials and other data):

$ echo "test message string" | gpg --encrypt --armor --recipient $KEYID -o encrypted.txt

To encrypt to multiple recipients (or to multiple keys):

$ echo "test message string" | gpg --encrypt --armor --recipient $KEYID_0 --recipient $KEYID_1 --recipient $KEYID_2 -o encrypted.txt

Decrypt the message:

$ gpg --decrypt --armor encrypted.txt
gpg: anonymous recipient; trying secret key 0x0000000000000000 ...
gpg: okay, we are the anonymous recipient.
gpg: encrypted with RSA key, ID 0x0000000000000000
test message string

Sign a message:

signed.txt”>
$ echo "test message string" | gpg --armor --clearsign > signed.txt

Verify the signature:

” [ultimate]
Primary key fingerprint: 011C E16B D45B 27A5 5BA8 776D FF3E 7D88 647E BCDB
Subkey fingerprint: 07AA 7735 E502 C5EB E09E B8B0 BECF A3C1 AE19 1D15″>
$ gpg --verify signed.txt
gpg: Signature made Wed 25 May 2016 00:00:00 AM UTC
gpg:                using RSA key 0xBECFA3C1AE191D15
gpg: Good signature from "Dr Duh " [ultimate]
Primary key fingerprint: 011C E16B D45B 27A5 5BA8  776D FF3E 7D88 647E BCDB
     Subkey fingerprint: 07AA 7735 E502 C5EB E09E  B8B0 BECF A3C1 AE19 1D15

Use a shell function to make encrypting files easier:

${output}”
}

reveal () {
output=$(echo “${1}” | rev | cut -c16- | rev)
gpg –decrypt –output ${output} “${1}” && echo “${1} -> ${output}”
}”>

secret () {
        output=~/"${1}".$(date +%s).enc
        gpg --encrypt --armor --output ${output} -r 0x0000 -r 0x0001 -r 0x0002 "${1}" && echo "${1} -> ${output}"
}

reveal () {
        output=$(echo "${1}" | rev | cut -c16- | rev)
        gpg --decrypt --output ${output} "${1}" && echo "${1} -> ${output}"
}
PGP does not provide forward secrecy – a compromised key may be used to decrypt all past messages. Although keys stored on YubiKey are difficult to steal, it is not impossible – the key and PIN could be taken, or a vulnerability may be discovered in key hardware or the random number generator used to create them, for example. Therefore, it is good practice to occassionally rotate sub-keys.

When a sub-key expires, it can either be renewed or replaced. Both actions require access to the offline master key. Renewing sub-keys by updating their expiration date indicates you are still in possession of the offline master key and is more convenient.

Replacing keys, on the other hand, is less convenient but more secure: the new sub-keys will not be able to decrypt previous messages, authenticate with SSH, etc. Contacts will need to receive the updated public key and any encrypted secrets need to be decrypted and re-encrypted to new sub-keys to be usable. This process is functionally equivalent to “losing” the YubiKey and provisioning a new one. However, you will always be able to decrypt previous messages using the offline encrypted backup of the original keys.

Neither rotation method is superior and it’s up to personal philosophy on identity management and individual threat model to decide which one to use, or whether to expire sub-keys at all. Ideally, sub-keys would be ephemeral: used only once for each encryption, signing and authentication event, however in practice that is not really feasible nor worthwhile with YubiKey. Advanced users may want to dedicate an offline device for more frequent key rotations and ease of provisioning.

Setup environment

To renew or rotate sub-keys, follow the same process as generating keys: boot to a secure environment, install required software and disconnect networking.

Connect the offline secret storage device with the master keys and identify the disk label:

$ sudo dmesg | tail
mmc0: new high speed SDHC card at address a001
mmcblk0: mmc0:a001 SS16G 14.8 GiB (ro)
mmcblk0: p1 p2

Decrypt and mount the offline volume:

$ sudo cryptsetup luksOpen /dev/mmcblk0p1 secret
Enter passphrase for /dev/mmcblk0p1:

$ sudo mount /dev/mapper/secret /mnt/encrypted-storage

Import the master key and configuration to a temporary working directory:

$ export GNUPGHOME=$(mktemp -d -t gnupg_$(date +%Y%m%d%H%M)_XXX)

$ gpg --import /mnt/encrypted-storage/tmp.XXX/mastersub.key

$ cp -v /mnt/encrypted-storage/tmp.XXX/gpg.conf $GNUPGHOME

Edit the master key:

$ export KEYID=0xFF3E7D88647EBCDB

$ gpg --expert --edit-key $KEYID

Secret key is available
[...]

Renewing sub-keys

Renewing sub-keys is simpler: you do not need to generate new keys, move keys to the YubiKey, or update any SSH public keys linked to the GPG key. All you need to do is to change the expiry time associated with the public key (which requires access to the master key you just loaded) and then to export that public key and import it on any computer where you wish to use the GPG (as distinct from the SSH) key.

To change the expiration date of all sub-keys, start by selecting all keys:

people can Join Knowasiak for free. Sign up on Knowasiak.com
Read More
Vanic
WRITTEN BY

Vanic

“Simplicity, patience, compassion.
These three are your greatest treasures.
Simple in actions and thoughts, you return to the source of being.
Patient with both friends and enemies,
you accord with the way things are.
Compassionate toward yourself,
you reconcile all beings in the world.”
― Lao Tzu, Tao Te Ching