- Purchase
- Download OS Image
- Required software
- Entropy
- Creating keys
- Master key
- Sign with existing key
- Sub-keys
- Verify
- Export secret keys
- Revocation certificate
- Backup
- Export public keys
- Configure Smartcard
- Transfer keys
- Verify card
- Multiple keys
- Cleanup
- Using keys
- Rotating keys
- SSH
- Multiple Keys
- Require touch
- Reset
- Notes
- Troubleshooting
- Links
Purchase
Download OS Image
$ curl -LfO https://cdimage.debian.org/debian-cd/current-live/amd64/iso-hybrid/debian-live-10.3.0-amd64-xfce.iso
$ 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
$ gpg --verify SHA512SUMS.sign SHA512SUMS
gpg: Signature made Sat Feb 8 18:02:16 2020 PST
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 Feb 8 18:02:16 2020 PST
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 --keyserver hkps://keyserver.ubuntu.com:443 --recv DF9B9C49EAA9298432589D76DA87E80D6294BE9B
$ grep $(sha512sum debian-live-10.3.0-amd64-xfce.iso) SHA512SUMS
SHA512SUMS:c6adede144eb32b7316b65342f7445cb13b95ef17551d47ce1a8468d3954710f5f68c979c1086aa1b94262c8bfd86679eb38b01731c7b9aaeaca690455f1ff7f debian-live-10.3.0-amd64-xfce.iso
$ 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.3.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
$ dmesg | tail -n2
sd2 at scsibus4 targ 1 lun 0: SCSI4 0/direct removable serial.0000000000000
sd2: 15193MB, 512 bytes/sector, 31116288 sectors
$ doas dd if=debian-live-10.3.0-amd64-xfce.iso of=/dev/rsd2c bs=4m
465+1 records in
465+1 records out
1951432704 bytes transferred in 139.125 secs (14026448 bytes/sec)
Required software
user
/live
.Debian and Ubuntu
$ 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
ykman
utility:$ sudo apt -y install python-pip python-pyscard
$ pip 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
# yubikey-installer.nix
{ nixpkgs ? , system ? "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;
}
$ nix build -f yubikey-installer.nix --out-link installer
$ sudo cp -v installer/iso/*.iso /dev/sdb; sync
'installer/iso/nixos-20.03.git.c438ce1-x86_64-linux.iso' -> '/dev/sdb'
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
$ brew install gnupg yubikey-personalization hopenpgp-tools ykman pinentry-mac
ykman
- pip install yubikey-manager
Windows
Entropy
$ cat /proc/sys/kernel/random/entropy_avail
849
$ sudo apt -y install at rng-tools python-gnupg openssl
$ 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
$ sudo atd
$ sudo service rng-tools restart
/dev/random
- the light on the device will dim briefly:$ cat /dev/random >/dev/null
[Press Control-C]
$ cat /proc/sys/kernel/random/entropy_avail
3049
Creating keys
Temporary working directory
$ export GNUPGHOME=$(mktemp -d)
$ export GNUPGHOME=~/gnupg-workspace
Harden configuration
$ 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
Master key
$ gpg --gen-random --armor 0 24
ydOmByxmDe63u7gqx2XI9eDgpvJwibNH
Shift
-Insert
.(8) RSA (set your own capabilities)
, Certify
capability only and 4096
bit key size.$ gpg --expert --full-generate-key
Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
(7) DSA (set your own capabilities)
(8) RSA (set your own capabilities)
(9) ECC and ECC
(10) ECC (sign only)
(11) ECC (set your own capabilities)
(13) Existing key
Your selection? 8
Possible actions for a RSA key: Sign Certify Encrypt Authenticate
Current allowed actions: Sign Certify Encrypt
(S) Toggle the sign capability
(E) Toggle the encrypt capability
(A) Toggle the authenticate capability
(Q) Finished
Your selection? E
Possible actions for a RSA key: Sign Certify Encrypt Authenticate
Current allowed actions: Sign Certify
(S) Toggle the sign capability
(E) Toggle the encrypt capability
(A) Toggle the authenticate capability
(Q) Finished
Your selection? S
Possible actions for a RSA key: Sign Certify Encrypt Authenticate
Current allowed actions: Certify
(S) Toggle the sign capability
(E) Toggle the encrypt capability
(A) Toggle the authenticate capability
(Q) Finished
Your selection? Q
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) 0
Key does not expire at all
Is this correct? (y/N) y
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
KEYID
) for use later:$ export KEYID=0xFF3E7D88647EBCDB
Sign with existing key
$ gpg --export-secret-keys --armor --output /tmp/new.sec
$ gpg --default-key $OLDKEY --sign-key $KEYID
Sub-keys
$ gpg --expert --edit-key $KEYID
Secret key is available.
sec rsa4096/0xEA5DE91459B80592
created: 2017-10-09 expires: never usage: C
trust: ultimate validity: ultimate
[ultimate] (1). Dr Duh
Signing
(4) RSA (sign only)
:gpg> addkey
Key is protected.
You need a passphrase to unlock the secret key for
user: "Dr Duh "
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
(6) RSA (encrypt only)
:gpg> addkey
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)
(10) ECC (sign only)
(11) ECC (set your own capabilities)
(12) ECC (encrypt only)
(13) Existing key
Your selection? 6
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
ssb rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
[ultimate] (1). Dr Duh
Authentication
(8) RSA (set your own capabilities)
and toggle the required capabilities until the only allowed action is Authenticate
:gpg> addkey
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)
(10) ECC (sign only)
(11) ECC (set your own capabilities)
(12) ECC (encrypt only)
(13) Existing key
Your selection? 8
Possible actions for a RSA key: Sign Encrypt Authenticate
Current allowed actions: Sign Encrypt
(S) Toggle the sign capability
(E) Toggle the encrypt capability
(A) Toggle the authenticate capability
(Q) Finished
Your selection? S
Possible actions for a RSA key: Sign Encrypt Authenticate
Current allowed actions: Encrypt
(S) Toggle the sign capability
(E) Toggle the encrypt capability
(A) Toggle the authenticate capability
(Q) Finished
Your selection? E
Possible actions for a RSA key: Sign Encrypt Authenticate
Current allowed actions:
(S) Toggle the sign capability
(E) Toggle the encrypt capability
(A) Toggle the authenticate capability
(Q) Finished
Your selection? A
Possible actions for a RSA key: Sign Encrypt Authenticate
Current allowed actions: Authenticate
(S) Toggle the sign capability
(E) Toggle the encrypt capability
(A) Toggle the authenticate capability
(Q) Finished
Your selection? Q
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
ssb rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
gpg> save
Add extra identities
adduid
:gpg> adduid
Real name: Dr Duh
Email address: DrDuh@other.org
Comment:
You selected this USER-ID:
"Dr Duh "
sec rsa4096/0xFF3E7D88647EBCDB
created: 2017-10-09 expires: never usage: SC
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: SC
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: SC
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: SC
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: SC
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
primary
to change that.Verify
$ gpg -K
/tmp.FLZC0xcM/pubring.kbx
-------------------------------------------------------------------------
sec rsa4096/0xFF3E7D88647EBCDB 2017-10-09 [C]
Key fingerprint = 011C E16B D45B 27A5 5BA8 776D FF3E 7D88 647E BCDB
uid Dr Duh
ssb rsa4096/0xBECFA3C1AE191D15 2017-10-09 [S] [expires: 2018-10-09]
ssb rsa4096/0x5912A795E90DD2CF 2017-10-09 [E] [expires: 2018-10-09]
ssb rsa4096/0x3F29127E79649A3D 2017-10-09 [A] [expires: 2018-10-09]
adduid
command.$ gpg --export $KEYID | hokey lint
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) withKey expiration times: []
on the primary key (see Note #3 about not setting an expiry for the primary key).
Export secret keys
$ gpg --armor --export-secret-keys $KEYID > $GNUPGHOME/mastersub.key
$ gpg --armor --export-secret-subkeys $KEYID > $GNUPGHOME/sub.key
.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 \path\to\dir\mastersub.gpg --armor --export-secret-keys $KEYID
$ gpg -o \path\to\dir\sub.gpg --armor --export-secret-subkeys $KEYID
Revocation certificate
$ gpg --gen-revoke $KEYID --output $GNUPGHOME/revoke.asc
revoke.asc
certificate file should be stored (or printed) in a (secondary) place that allows retrieval in case the main backup fails.Backup
$ 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
$ sudo dd if=/dev/urandom of=/dev/mmcblk0 bs=4M status=progress
$ 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): o
Created a new DOS disklabel with disk identifier 0xd756b789.
Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.
$ 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.
$ 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:
$ sudo cryptsetup luksOpen /dev/mmcblk0p1 secret
Enter passphrase for /dev/mmcblk0p1:
$ 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
$ sudo mkdir /mnt/encrypted-storage
$ sudo mount /dev/mapper/secret /mnt/encrypted-storage
$ sudo cp -avi $GNUPGHOME /mnt/encrypted-storage/
$ sudo cp onerng_3.6-1_all.deb /mnt/encrypted-storage/
keytocard
will delete the local copy on save.$ sudo umount /mnt/encrypted-storage/
$ sudo cryptsetup luksClose secret
$ dmesg | grep sd.\ at
sd2 at scsibus5 targ 1 lun 0: SCSI4 0/direct removable serial.00000000000000000000
$ doas disklabel -h sd2
a
partition with FS type RAID
and size of 25 Megabytes:$ doas fdisk -iy sd2
Writing MBR at offset 0.
$ doas disklabel -E sd2
Label editor (enter '?' for help at any prompt)
sd2> a a
offset: [64]
size: [31101776] 25M
FS type: [4.2BSD] RAID
sd2*> w
sd2> q
No label changes
$ doas bioctl -c C -l sd2a softraid0
New passphrase:
Re-type passphrase:
softraid0: CRYPTO volume attached as sd3
i
partition on the new crypto volume and the filesystem:$ doas fdisk -iy sd3
Writing MBR at offset 0.
$ doas disklabel -E sd3
Label editor (enter '?' for help at any prompt)
sd3> a i
offset: [64]
size: [16001]
FS type: [4.2BSD]
sd3*> w
sd3> q
No label changes.
$ doas newfs sd3i
$ doas mkdir /mnt/encrypted-storage
$ doas mount /dev/sd3i /mnt/encrypted-storage
$ doas cp -avi $GNUPGHOME /mnt/encrypted-storage
keytocard
will delete the local copy on save.$ doas umount /mnt/encrypted-storage
$ doas bioctl -d sd3
Export public keys
$ 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/$KEYID-$(date +%F).txt
$ doas disklabel -E sd2
Label editor (enter '?' for help at any prompt)
sd2> a b
offset: [32130]
size: [31069710] 25M
FS type: [swap] 4.2BSD
sd2*> w
sd2> q
No label changes.
$ doas newfs sd2b
$ doas mkdir /mnt/public
$ doas mount /dev/sd2b /mnt/public
$ gpg --armor --export $KEYID | doas tee /mnt/public/$KEYID.txt
$ gpg -o \path\to\dir\pubkey.gpg --armor --export $KEYID
$ 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
Configure Smartcard
$ 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
Signature key ....: [none]
Encryption key....: [none]
Authentication key: [none]
General key info..: [none]
Change PIN
123456
and default Admin PIN (PUK) is 12345678
. CCID-mode PINs can be up to 127 ASCII characters.gpg/card> admin
Admin commands are allowed
gpg/card> passwd
gpg: OpenPGP card no. D2760001240102010006055532110000 detected
1 - change PIN
2 - unblock PIN
3 - change Admin PIN
4 - set the Reset Code
Q - quit
Your selection? 3
PIN changed.
1 - change PIN
2 - unblock PIN
3 - change Admin PIN
4 - set the Reset Code
Q - quit
Your selection? 1
PIN changed.
1 - change PIN
2 - unblock PIN
3 - change Admin PIN
4 - set the Reset Code
Q - quit
Your selection? q
Set information
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
Signature key ....: [none]
Encryption key....: [none]
Authentication key: [none]
General key info..: [none]
gpg/card> quit
Transfer keys
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.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.$ gpg --edit-key $KEYID
Secret key is available.
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
ssb rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
Signing
gpg> key 1
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
ssb rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
gpg> keytocard
Please select where to store the key:
(1) Signature key
(3) Authentication key
Your selection? 1
You need a passphrase to unlock the secret key for
user: "Dr Duh "
4096-bit RSA key, ID 0xBECFA3C1AE191D15, created 2016-05-24
Encryption
key 1
again to de-select and key 2
to select the next key:gpg> key 1
gpg> key 2
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
ssb* rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
gpg> keytocard
Please select where to store the key:
(2) Encryption key
Your selection? 2
[...]
Authentication
key 2
again to deselect and key 3
to select the last key:gpg> key 2
gpg> key 3
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
ssb rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb* rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
gpg> keytocard
Please select where to store the key:
(3) Authentication key
Your selection? 3
gpg> save
Verify card
ssb>
:$ gpg -K
/tmp.FLZC0xcM/pubring.kbx
-------------------------------------------------------------------------
sec rsa4096/0xFF3E7D88647EBCDB 2017-10-09 [C]
Key fingerprint = 011C E16B D45B 27A5 5BA8 776D FF3E 7D88 647E BCDB
uid Dr Duh
ssb> rsa4096/0xBECFA3C1AE191D15 2017-10-09 [S] [expires: 2018-10-09]
ssb> rsa4096/0x5912A795E90DD2CF 2017-10-09 [E] [expires: 2018-10-09]
ssb> rsa4096/0x3F29127E79649A3D 2017-10-09 [A] [expires: 2018-10-09]
Multiple keys
$ mv -vi $GNUPGHOME $GNUPGHOME.1
renamed '/tmp.FLZC0xcM' -> '/tmp.FLZC0xcM.1'
$ cp -avi /mnt/encrypted-storage/tmp.XXX $GNUPGHOME
'/mnt/encrypted-storage/tmp.FLZC0xcM' -> '/tmp.FLZC0xcM'
$ cd $GNUPGHOME
Cleanup
- Saved encryption, signing and authentication sub-keys to YubiKey (
gpg -K
should showssb>
for sub-keys). - Saved the YubiKey user and admin PINs which you changed from defaults.
- Saved the password to the GPG master key.
- 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.
$GNUPGHOME
and remove the secret keys from the GPG keyring:$ sudo srm -r $GNUPGHOME || sudo rm -rf $GNUPGHOME
$ gpg --delete-secret-key $KEYID
Using keys
$ cd ~/.gnupg ; wget https://raw.githubusercontent.com/drduh/config/master/gpg.conf
$ chmod 600 gpg.conf
$ sudo apt update && sudo apt install -y gnupg2 gnupg-agent gnupg-curl scdaemon pcscd
$ sudo mount /dev/mmcblk0p2 /mnt
$ doas pkg_add gnupg pcsc-tools
$ doas mount /dev/sd2b /mnt
$ gpg --import /mnt/0x*txt
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
trust
and 5
:$ export KEYID=0xFF3E7D88647EBCDB
$ gpg --edit-key $KEYID
gpg> trust
pub 4096R/0xFF3E7D88647EBCDB created: 2016-05-24 expires: never usage: C
trust: unknown validity: unknown
sub 4096R/0xBECFA3C1AE191D15 created: 2017-10-09 expires: 2018-10-09 usage: S
sub 4096R/0x5912A795E90DD2CF created: 2017-10-09 expires: 2018-10-09 usage: E
sub 4096R/0x3F29127E79649A3D created: 2017-10-09 expires: 2018-10-09 usage: A
[ unknown] (1). 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
pub 4096R/0xFF3E7D88647EBCDB created: 2016-05-24 expires: never usage: C
trust: ultimate validity: unknown
sub 4096R/0xBECFA3C1AE191D15 created: 2017-10-09 expires: 2018-10-09 usage: S
sub 4096R/0x5912A795E90DD2CF created: 2017-10-09 expires: 2018-10-09 usage: E
sub 4096R/0x3F29127E79649A3D created: 2017-10-09 expires: 2018-10-09 usage: A
[ unknown] (1). Dr Duh
gpg> quit
$ gpg --card-status
Reader ...........: Yubico YubiKey OTP FIDO CCID 00 00
Application ID ...: D2760001240102010006055532110000
Version ..........: 3.4
Manufacturer .....: Yubico
Serial number ....: 05553211
Name of cardholder: Dr Duh
Language prefs ...: en
Sex ..............: unspecified
URL of public key : [not set]
Login data .......: doc@duh.to
Signature PIN ....: not forced
Key attributes ...: rsa4096 rsa4096 rsa4096
Max. PIN lengths .: 127 127 127
PIN retry counter : 3 3 3
Signature counter : 0
Signature key ....: 07AA 7735 E502 C5EB E09E B8B0 BECF A3C1 AE19 1D15
created ....: 2016-05-24 23:22:01
Encryption key....: 6F26 6F46 845B BEB8 BDF3 7E9B 5912 A795 E90D D2CF
created ....: 2016-05-24 23:29:03
Authentication key: 82BE 7837 6A3F 2E7B E556 5E35 3F29 127E 7964 9A3D
created ....: 2016-05-24 23:36:40
General key info..: pub 4096R/0xBECFA3C1AE191D15 2016-05-24 Dr Duh
sec# 4096R/0xFF3E7D88647EBCDB created: 2016-05-24 expires: never
ssb> 4096R/0xBECFA3C1AE191D15 created: 2017-10-09 expires: 2018-10-09
card-no: 0006 05553211
ssb> 4096R/0x5912A795E90DD2CF created: 2017-10-09 expires: 2018-10-09
card-no: 0006 05553211
ssb> 4096R/0x3F29127E79649A3D created: 2017-10-09 expires: 2018-10-09
card-no: 0006 05553211
sec#
indicates master key is not available (as it should be stored encrypted offline).General key info..: [none]
in the output instead - go back and import the public key using the previous step.$ echo "test message string" | gpg --encrypt --armor --recipient $KEYID -o encrypted.txt
$ echo "test message string" | gpg --encrypt --armor --recipient $KEYID_0 --recipient $KEYID_1 --recipient $KEYID_2 -o encrypted.txt
$ 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
$ echo "test message string" | gpg --armor --clearsign > signed.txt
$ 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
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}"
}
$ secret document.pdf
document.pdf -> document.pdf.1580000000.enc
$ reveal document.pdf.1580000000.enc
gpg: anonymous recipient; trying secret key 0xFF3E7D88647EBCDB ...
gpg: okay, we are the anonymous recipient.
gpg: encrypted with RSA key, ID 0x0000000000000000
document.pdf.1580000000.enc -> document.pdf
Rotating keys
Setup environment
$ sudo dmesg | tail
mmc0: new high speed SDHC card at address a001
mmcblk0: mmc0:a001 SS16G 14.8 GiB (ro)
mmcblk0: p1 p2
$ sudo cryptsetup luksOpen /dev/mmcblk0p1 secret
Enter passphrase for /dev/mmcblk0p1:
$ sudo mount /dev/mapper/secret /mnt/encrypted-storage
$ export GNUPGHOME=$(mktemp -d)
$ gpg --import /mnt/encrypted-storage/tmp.XXX/mastersub.key
$ cp -v /mnt/encrypted-storage/tmp.XXX/gpg.conf $GNUPGHOME
$ export KEYID=0xFF3E7D88647EBCDB
$ gpg --edit-key $KEYID
Secret key is available
[...]
Renewing sub-keys
$ gpg --edit-key $KEYID
Secret key is available.
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
ssb rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
gpg> key 1
Secret key is available.
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
ssb rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
gpg> key 2
Secret key is available.
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
ssb* rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
gpg> key 3
Secret key is available.
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
ssb* rsa4096/0x5912A795E90DD2CF
created: 2017-10-09 expires: 2018-10-09 usage: E
ssb* rsa4096/0x3F29127E79649A3D
created: 2017-10-09 expires: 2018-10-09 usage: A
[ultimate] (1). Dr Duh
expire
command to set a new expiration date. (Despite the name, this will not cause currently valid keys to become expired).gpg> expire
Changing expiration time for a subkey.
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)
quit
to save your changes.$ gpg --export $KEYID > pubkey.gpg
$ gpg --import pubkey.gpg
Rotating keys
$ gpg --armor --export-secret-keys $KEYID > $GNUPGHOME/mastersub.key
$ gpg --armor --export-secret-subkeys $KEYID > $GNUPGHOME/sub.key
$ sudo cp -avi $GNUPGHOME /mnt/encrypted-storage
$ ls /mnt/encrypted-storage
lost+found tmp.ykhTOGjR36 tmp.2gyGnyCiHs
$ sudo umount /mnt/encrypted-storage
$ sudo cryptsetup luksClose /dev/mapper/secret
$ sudo mkdir /mnt/public
$ sudo mount /dev/mmcblk0p2 /mnt/public
$ gpg --armor --export $KEYID | sudo tee /mnt/public/$KEYID-$(date +%F).txt
$ sudo umount /mnt/public
SSH
enable-ssh-support
), as well as Putty's Pageant on Windows (enable-putty-support
). This means it can be used instead of the traditional ssh-agent / pageant. There are some differences from ssh-agent, notably that gpg-agent does not cache keys rather it converts, encrypts and stores them - persistently - as GPG keys and then makes them available to ssh clients. Any existing ssh private keys that you'd like to keep in gpg-agent
should be deleted after they've been imported to the GPG agent.gpg-agent
, you'll be prompted for a passphrase to protect that key within GPG's key store - you may want to use the same passphrase as the original's ssh version. GPG can both cache passphrases for a determined period (ref. gpg-agent
's various cache-ttl
options), and since version 2.1 can store and fetch passphrases via the macOS keychain. Note than when removing the old private key after importing to gpg-agent
, keep the .pub
key file around for use in specifying ssh identities (e.g. ssh -i /path/to/identity.pub
).gpg-agent
's ssh agent support is being able to remove keys. ssh-add -d/-D
have no effect. Instead, you need to use the gpg-connect-agent
utility to lookup a key's keygrip, match that with the desired ssh key fingerprint (as an MD5) and then delete that keygrip. The gnupg-users mailing list has more information.Create configuration
$ cd ~/.gnupg
$ wget https://raw.githubusercontent.com/drduh/config/master/gpg-agent.conf
$ grep -ve "^#" gpg-agent.conf
enable-ssh-support
default-cache-ttl 60
max-cache-ttl 120
pinentry-program /usr/bin/pinentry-curses
cache-ttl
options do NOT apply when using a YubiKey as a smartcard as the PIN is cached by the smartcard itself. Therefore, in order to clear the PIN from cache (smartcard equivalent to default-cache-ttl
and max-cache-ttl
), you need to unplug the YubiKey.pinentry-program /usr/bin/pinentry-gnome3
for a GUI-based prompt. If the pinentry graphical dialog doesn't show and you get this error: sign_and_send_pubkey: signing failed: agent refused operation
, you may need to install the dbus-user-session
package and restart the computer for the dbus
user session to be fully inherited; this is because behind the scenes, pinentry
complains about No $DBUS_SESSION_BUS_ADDRESS found
, falls back to curses
but doesn't find the expected tty
.brew install pinentry-mac
and set the program path to pinentry-program /usr/local/bin/pinentry-mac
or pinentry-program /usr/local/MacGPG2/libexec/pinentry-mac.app/Contents/MacOS/pinentry-mac
if using MacGPG Suite.Replace agents
gpg-agent
for use by SSH, use the gpg-connect-agent /bye
or gpgconf --launch gpg-agent
commands.rc
file:export GPG_TTY="$(tty)"
export SSH_AUTH_SOCK="/run/user/$UID/gnupg/S.gpg-agent.ssh"
gpg-connect-agent updatestartuptty /bye > /dev/null
gpgconf --list-dirs agent-ssh-socket
will automatically set SSH_AUTH_SOCK
to the correct value and is better than hard-coding to run/user/$UID/gnupg/S.gpg-agent.ssh
, if available:export GPG_TTY="$(tty)"
export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
gpgconf --launch gpg-agent
SSH_AUTH_SOCK
normally only needs to be set on the local laptop (workstation), where the YubiKey is plugged in. On the remote server that we SSH into, ssh
will automatically set SSH_AUTH_SOCK
to something like /tmp/ssh-mXzCzYT2Np/agent.7541
when we connect. We therefore do NOT manually set SSH_AUTH_SOCK
on the server - doing so would break SSH Agent Forwarding.Copy public key
ssh-add
to the server's authorized_keys
file:$ ssh-add -L
ssh-rsa AAAAB4NzaC1yc2EAAAADAQABAAACAz[...]zreOKM+HwpkHzcy9DQcVG2Nw== cardno:000605553211
(Optional) Save public key for identity file configuration
-i [identity_file]
or the IdentityFile
and IdentitiesOnly
options in .ssh/config
.IdentityFile
is traditionally the path to the private key file (for example IdentityFile ~/.ssh/id_rsa
). For the YubiKey - indeed, in general for keys stored in an ssh agent - IdentityFile
should point to the public key file, ssh
will select the appropriate private key from those available via the ssh agent. To prevent ssh
from trying all keys in the agent use the IdentitiesOnly yes
option along with one or more -i
or IdentityFile
options for the target host.IdentitiesOnly yes
, ssh
will not automatically enumerate public keys loaded into ssh-agent
or gpg-agent
. This means publickey
authentication will not proceed unless explicitly named by ssh -i [identity_file]
or in .ssh/config
on a per-host basis.$ ssh-add -L | grep "cardno:000605553211" > ~/.ssh/id_rsa_yubikey.pub
github.com
for example, as follows:$ cat << EOF >> ~/.ssh/config
Host github.com
IdentitiesOnly yes
IdentityFile ~/.ssh/id_rsa_yubikey.pub
EOF
Connect with public key authentication
$ ssh git@github.com -vvv
[...]
debug2: key: cardno:000605553211 (0x1234567890),
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: cardno:000605553211
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug2: input_userauth_pk_ok: fp e5:de:a5:74:b1:3e:96:9b:85:46:e7:28:53:b4:82:c3
debug3: sign_and_send_pubkey: RSA e5:de:a5:74:b1:3e:96:9b:85:46:e7:28:53:b4:82:c3
debug1: Authentication succeeded (publickey).
[...]
Import SSH keys
gpg-agent
, you'll need to import them. You should then remove the original private keys. When importing the key, gpg-agent
uses the key's filename as the key's label; this makes it easier to follow where the key originated from. In this example, we're starting with just the YubiKey's key in place and importing ~/.ssh/id_rsa
:$ ssh-add -l
4096 SHA256:... cardno:00060123456 (RSA)
$ ssh-add ~/.ssh/id_rsa && rm ~/.ssh/id_rsa
ssh-add
, it will prompt for the SSH key's passphrase if present, then the pinentry
program will prompt and confirm for a new passphrase to use to encrypt the converted key within the GPG key store.ssh-add -l
:$ ssh-add -l
4096 SHA256:... cardno:00060123456 (RSA)
2048 SHA256:... /Users/username/.ssh/id_rsa (RSA)
gpg-connect-agent
's KEYINFO
and DELETE_KEY
commands:$ ssh-add -E md5 -l
4096 MD5:... cardno:00060123456 (RSA)
2048 MD5:... /Users/username/.ssh/id_rsa (RSA)
pinentry
will be invoked to request the key's passphrase. The passphrase will be cached for up to 10 minutes idle time between uses, to a maximum of 2 hours.Remote Machines (Agent Forwarding)
/etc/ssh/sshd_config
to set StreamLocalBindUnlink yes
/etc/ssh/sshd_config
, you will need to remove the socket on the remote machine before forwarding works. For example, rm /run/user/1000/gnupg/S.gpg-agent
. Further information can be found on the AgentForwarding GNUPG wiki page.$ scp ~/.gnupg/pubring.kbx remote:~/.gnupg/
ssh -A remote
on the local machine to log into remote, and should then be able to use YubiKey as if it were connected to the remote machine. For example, using e.g. ssh-add -l
on that remote machine should show the public key from the YubiKey (note cardno:
). (If you don't want to have to remember to use ssh -A
, you can use ForwardAgent yes
in ~/.ssh/config
. As a security best practice, always use ForwardAgent yes
only for a single Hostname
, never for all servers.)RemoteForward
in ~/.ssh/config
as detailed in the next chapter, because the right thing actually happens automatically.Steps for older distributions
$ gpgconf --list-dirs agent-extra-socket
/run/user/1000/gnupg/S.gpg-agent.extra
- though on older Linux distros (and macOS) it may be /home//.gnupg/S/gpg-agent.extra
$ gpgconf --list-dirs agent-socket
/run/user/1000/gnupg/S.gpg-agent
~/.ssh/config
(your agent sockets may be different):Host
Hostname remote-host.tld
ForwardAgent yes
RemoteForward /run/user/1000/gnupg/S.gpg-agent /run/user/1000/gnupg/S.gpg-agent.extra
# RemoteForward [remote socket] [local socket]
gpg-agent.conf
file on both the remote and local machines to add the following information:enable-ssh-support
pinentry-program /usr/bin/pinentry-curses
extra-socket /run/user/1000/gnupg/S.gpg-agent.extra
GitHub
> git config --global user.signingkey $KEYID
-S
option. GPG will automatically query YubiKey and prompt you for a PIN.> git config --global core.sshcommand 'plink -agent'
> git config --global gpg.program 'C:\Program Files (x86)\GnuPG\bin\gpg.exe'
git@github.com:USERNAME/repository
and any authenticated commands will be authorized by YubiKey.gpg: signing failed: No secret key
- run gpg --card-status
with YubiKey plugged in and try the git command again.OpenBSD
$ doas pkg_add pcsc-tools
$ doas rcctl enable pcscd
$ doas reboot
Windows
Yubico YubiKey OTP+FIDO+CCID 0
. The name slightly differs according to the model. Thanks to Scott Hanselman for sharing this information.- Create or edit
%APPDATA%/gnupg/scdaemon.conf
to add:
reader-port
- Edit
%APPDATA%/gnupg/gpg-agent.conf
to add:
enable-ssh-support
enable-putty-support
- Open a command console, restart the agent:
> gpg-connect-agent killagent /bye
> gpg-connect-agent /bye
- Enter
> gpg --card-status
to see YubiKey details. - Import the public key:
> gpg --import
- Trust the master key
- Retrieve the public key id:
> gpg --list-public-keys
- Export the SSH key from GPG:
> gpg --export-ssh-key
gpg-connect-agent /bye
and place it in the startup folder shell:startup
to make sure the agent starts after a system shutdown. Modify the shortcut properties so it starts in a "Minimized" window, to avoid unnecessary noise at startup.WSL

Prerequisites
- Ubuntu 16.04 or newer for WSL
- Kleopatra
- Windows configuration
WSL configuration
eval $(/mnt/c//weasel-pageant -r -a /tmp/S.weasel-pageant)
to shell rc file. Use a named socket here so it can be used in the RemoteForward
directive of ~/.ssh/config
. Source it with source ~/.bashrc
.$ ssh-add -l
~/.ssh/config
to add the following for each host you want to use agent forwarding:ForwardAgent yes
RemoteForward /tmp/S.weasel-pageant
gpgconf --list-dirs agent-ssh-socket
Remote host configuration
export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
export GPG_TTY=$(tty)
/etc/ssh/sshd_config
:AllowAgentForwarding yes
StreamLocalBindUnlink yes
sudo service sshd reload
).ssh-add -l
- you should see nothing.ssh-add -l
- if you see the ssh key, that means forwarding works!Multiple Keys
$ gpg-connect-agent "scd serialno" "learn --force" /bye
$PATH
. E.g.:$ cat >> ~/.scripts/remove-keygrips.sh <<EOF
#!/usr/bin/env bash
test ! "$@" && echo "Specify a key." && exit 1
KEYGRIPS="$(gpg --with-keygrip --list-secret-keys $@ | grep Keygrip | awk '{print $3}')"
for keygrip in $KEYGRIPS
do
rm "$HOME/.gnupg/private-keys-v1.d/$keygrip.key" 2> /dev/null
done
gpg --card-status
EOF
$ chmod +x ~/.scripts/remove-keygrips.sh
$ remove-keygrips.sh $KEYID
Require touch
touch
instead of set-touch
in the following commands.$ ykman openpgp set-touch aut on
$ ykman openpgp set-touch sig on
$ ykman openpgp set-touch enc on
Mailvelope on macOS
$ brew install gpgme
~/Library/Application\ Support/Google/Chrome/NativeMessagingHosts/gpgmejson.json
and add:{
"name": "gpgmejson",
"description": "Integration with GnuPG",
"path": "/usr/local/bin/gpgme-json",
"type": "stdio",
"allowed_origins": [
"chrome-extension://kajibbejlbohfaggdiogboambcijhkke/"
]
}
$ sudo launchctl config user path /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
Reset
gpg-connect-agent -R $file
to lock and terminate the card. Then re-insert YubiKey to reset./hex
scd serialno
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 81 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 20 00 83 08 40 40 40 40 40 40 40 40
scd apdu 00 e6 00 00
scd apdu 00 44 00 00
/echo Card has been successfully reset.
ykman
:$ ykman openpgp reset
WARNING! This will delete all stored OpenPGP keys and data and restore factory settings? [y/N]: y
Resetting OpenPGP data, don't remove your YubiKey...
Success! All data has been cleared and default PINs are set.
PIN: 123456
Reset code: NOT SET
Admin PIN: 12345678
Notes
- YubiKey has two configurations: one invoked with a short press, and the other with a long press. By default, the short-press mode is configured for HID OTP - a brief touch will emit an OTP string starting with
cccccccc
. If you rarely use the OTP mode, you can swap it to the second configuration via the YubiKey Personalization tool. If you never use OTP, you can disable it entirely using the YubiKey Manager application (note, this not the similarly named older YubiKey NEO Manager). - Programming YubiKey for GPG keys still lets you use its other configurations - U2F, OTP and static password modes, for example.
- Setting an expiry essentially forces you to manage your subkeys and announces to the rest of the world that you are doing so. Setting an expiry on a primary key is ineffective for protecting the key from loss - whoever has the primary key can simply extend its expiry period. Revocation certificates are better suited for this purpose. It may be appropriate for your use case to set expiry dates on subkeys.
- To switch between two or more identities on different keys - unplug the first key and restart gpg-agent, ssh-agent and pinentry with
pkill gpg-agent ; pkill ssh-agent ; pkill pinentry ; eval $(gpg-agent --daemon --enable-ssh-support)
, then plug in the other key and rungpg-connect-agent updatestartuptty /bye
- then it should be ready for use. - To use yubikeys on more than one computer with gpg: After the initial setup, import the public keys on the second workstation. Confirm gpg can see the card via
gpg --card-status
, Trust the public keys you imported ultimately (as above). At this pointgpg --list-secret-keys
should show your (trusted) key.
Troubleshooting
- Use
man gpg
to understand GPG options and command-line flags. - If you encounter problems connecting to YubiKey with GPG - try unplugging and re-inserting YubiKey, and restarting the
gpg-agent
process. - If you receive the error,
gpg: decryption failed: secret key not available
- you likely need to install GnuPG version 2.x. - If you receive the error,
Yubikey core error: no yubikey present
- make sure the YubiKey is inserted correctly. It should blink once when plugged in. - If you still receive the error,
Yubikey core error: no yubikey present
- you likely need to install newer versions of yubikey-personalize as outlined in Required software. - If you receive the error,
Yubikey core error: write error
- YubiKey is likely locked. Install and run yubikey-personalization-gui to unlock it. - If you receive the error,
Key does not match the card's capability
- you likely need to use 2048 bit RSA key sizes. - If you receive the error,
sign_and_send_pubkey: signing failed: agent refused operation
- make sure you replacedssh-agent
withgpg-agent
as noted above. - If you still receive the error,
sign_and_send_pubkey: signing failed: agent refused operation
- run the commandgpg-connect-agent updatestartuptty /bye
- If you still receive the error,
sign_and_send_pubkey: signing failed: agent refused operation
- edit~/.gnupg/gpg-agent.conf
to set a validpinentry
program path, e.g.pinentry-program /usr/local/bin/pinentry-mac
on macOS. - If you receive the error,
The agent has no identities
fromssh-add -L
, make sure you have installed and startedscdaemon
. - If you receive the error,
Error connecting to agent: No such file or directory
fromssh-add -L
, the UNIX file socket that the agent uses for communication with other processes may not be set up correctly. On Debian, tryexport SSH_AUTH_SOCK="/run/user/$UID/gnupg/S.gpg-agent.ssh"
. Also see thatgpgconf --list-dirs agent-ssh-socket
is returning single path, to existingS.gpg-agent.ssh
socket. - If you receive the error,
Permission denied (publickey)
, increase ssh verbosity with the-v
flag and ensure the public key from the card is being offered:Offering public key: RSA SHA256:abcdefg... cardno:00060123456
. If it is, ensure you are connecting as the right user on the target system, rather than as the user on the local system. Otherwise, be sureIdentitiesOnly
is not enabled for this host. - If SSH authentication still fails - add up to 3
-v
flags to thessh
client to increase verbosity. - If it still fails, it may be useful to stop the background
sshd
daemon process service on the server (e.g. usingsudo systemctl stop sshd
) and instead start it in the foreground with extensive debugging output, using/usr/sbin/sshd -eddd
. Note that the server will not fork and will only process one connection, therefore has to be re-started after everyssh
test. - If you receive the error,
Please insert the card with serial number: *
see management of multiple keys. - If you receive the error,
There is no assurance this key belongs to the named user
orencryption failed: Unusable public key
usegpg --edit-key
to settrust
to5 = I trust ultimately
.
Links
- https://alexcabal.com/creating-the-perfect-gpg-keypair/
- https://blog.habets.se/2013/02/GPG-and-SSH-with-Yubikey-NEO
- https://blog.josefsson.org/2014/06/23/offline-gnupg-master-key-and-subkeys-on-yubikey-neo-smartcard/
- https://blog.onefellow.com/post/180065697833/yubikey-forwarding-ssh-keys
- https://developers.yubico.com/PGP/Card_edit.html
- https://developers.yubico.com/PIV/Introduction/Admin_access.html
- https://developers.yubico.com/yubico-piv-tool/YubiKey_PIV_introduction.html
- https://developers.yubico.com/yubikey-personalization/
- https://developers.yubico.com/yubikey-piv-manager/PIN_and_Management_Key.html
- https://evilmartians.com/chronicles/stick-with-security-yubikey-ssh-gnupg-macos
- https://gist.github.com/ageis/14adc308087859e199912b4c79c4aaa4
- https://github.com/herlo/ssh-gpg-smartcard-config
- https://github.com/tomlowenthal/documentation/blob/master/gpg/smartcard-keygen.md
- https://help.riseup.net/en/security/message-security/openpgp/best-practices
- https://jclement.ca/articles/2015/gpg-smartcard/
- https://rnorth.org/gpg-and-ssh-with-yubikey-for-mac
- https://trmm.net/Yubikey
- https://www.bootc.net/archives/2013/06/09/my-perfect-gnupg-ssh-agent-setup/
- https://www.esev.com/blog/post/2015-01-pgp-ssh-key-on-yubikey-neo/
- https://www.hanselman.com/blog/HowToSetupSignedGitCommitsWithAYubiKeyNEOAndGPGAndKeybaseOnWindows.aspx
- https://www.void.gr/kargig/blog/2013/12/02/creating-a-new-gpg-key-with-subkeys/
- https://mlohr.com/gpg-agent-forwarding/
首先要从什么是OTP说起。
OTP是One-Time Password的简称,中文对应的准确翻译应该叫"一次一密"。根据香农(这个人…信息论、现代密码学,以及其他乱七八糟东西的发明者,牛逼至极的人物啊!)创立的现代密码学理论,一次一密是不可能被破解的,除此之外所有的其他加密方案都至少能被暴力破解,虽然破解的难度是指数级的。(当然,香农说的一次一密不可破解是有前提条件的,具体参考维基百科上的"一次性密码本"词条)。具体来说,一次一密就是在每次加密会话过程中,对传送的明文使用不同的密钥进行加密,每次使用的密钥是随机、不可预测、不重复使用的,从而保证了加密是绝对不可破解的。
当然,我说的是简单化的一次一密的实现,实际操作过程中,密钥的长度必须大于等于明文长度,而且密钥必须是可验证的(所以也可以看成是可预测的)。真正的一次一密,等于需要一个安全信道来传送不少于明文长度的密钥,几乎是没有意义的。
其实生活中已经有很多一次一密的例子,例如中国银行的E-TOKEN、魔兽世界安全令牌、中国建设银行的动态口令卡(纸制),这些都是一次一密的。
国内的一次一密电子令牌基本上使用的是SecurID,EMC公司下属的RSA公司出品的。这种一次一密解决方案使用一个预先定义的time-based的函数计算密码,称为Time-synchronized one-time password。每个token出厂前与服务器同步时间,在出厂后,token和服务器以相同的时钟计算,每分钟变化一次。
在验证token上读取的数字时,服务端可以设置允许的误差值,例如允许前后5分钟内产生的密钥输入都认为是有效的,这样可以最大限度避免token的时钟漂移。
经仔细查证后,上文描述有误。准确的实现是:RSA的服务端验证时允许前后30秒或前后60秒内的密钥为有效密钥。服务端会保留当前token,前一token,后一token三个token值,如果用户输入与当前token一致则不做变化。如果用户输入的是前一token或后一token,服务器将记录这个SecurID的ID对应的offset,下次验证时考量这个offset。如果用户超过了这三个token的值范围,用户将被提示输入SecurID显示的下一个token,如果与上一个输入的token顺序一致,系统将判断验证通过,并记录这个较大的offset值。
这样的方案安全性很高,很多公司内部的vpn系统、线上服务器登陆系统等等都使用了SecurID进行认证。缺点很明显:价格高,据说每个的成本在¥200(网易出的那个山寨版我就不评论了…售价居然才60左右…只能说不太靠谱了…),而且需要配套RSA的服务端方案;需要电池保证时钟运作,因此存在更换token的情况。
另一种完全不同的一次一密方案是使用数学方法生成密钥序列,称为Mathematical-algorithm-based one-time password。这种算法使用数学函数生成密钥序列,然后依次使用密钥序列,从而不需要考虑时间因素。由于密钥序列生成过程中没有时间因素,实际生产的硬件token可以不包含电池供电,免去服务端与token的对时,成本可以下降,同时也没有电池耗尽更换token的担忧(更换token=安全隐患,因为需要人的参与,人永远是任何安全体系的最大漏洞…)。维基百科上举例了一个使用hash chain方法产生此类OTP的方案:找到一个单向函数f(例如任意一个hash函数),给定一个初始种子s。根据f和s产生序列:f(s), f(f(s)), f(f(f(s)))…。然后将该序列倒置,依次作为密钥使用。第三方如果偶然获取到序列中某个密钥,他就必须要通过f的反函数来计算下一个密钥,而f的单向性保证了这样的计算是不可行的。
yubikey使用的是第二种方案。它是一个廉价的OTP解决方案,10枚yubikey的平均价格是$28,由yubico提供验证服务器并提供API供开发者调用。它不需要电池供电,也没有液晶屏显示密钥。在插入电脑之后,它会被识别为一个USB键盘,在任意输入框聚焦并按一下yubikey上的硬件按钮,yubikey将自动模拟键盘输入一串一次性密钥。由于yubikey在电脑上被识别为USB键盘,它可以做到最好的免驱动支持(现在没有操作系统不支持USB键盘了吧?),可以在Windows/MacOSX/Linux上使用。关于yubikey使用的OTP生成方案,强烈建议阅读一下官方提供的文档来了解:http://yubico.com/files/Security_Evaluation_2009-09-09.pdf
要注意的是,yubikey每次插拔都会在内置的非易失性存储器上的Session Counter增加1,该Session Counter总长度为16bit,在每天插拔20次的频率下,该Counter在9年左右到达满值。这个寿命还是很让人满意的。
yubikey是一个非常开放的硬件设备,它本身的硬件实现原理、服务端架设代码、服务端API代码,都是完全开放的。从而在它之上衍生了很多开源项目与之搭配使用。从yubico的wiki页面可以看到一个简单的列表。稍微列举一下:
- YubiRADIUS:使用yubikey产生的OTP验证用户的RADIUS服务器。该服务器由yubico提供,任何拥有yubikey的用户都可以在上面开通管理员帐号进行使用。详细使用指南:http://wiki.yubico.com/wiki/index.php/Applications:YubiRADIUS_RADIUS_Service
- RADIUS on Premise:使用LDAP维护yubikey ID与用户的联系,自行搭建使用yubikey做验证的RADIUS服务器。OTP+VPN+RADIUS,这几乎是最安全的上网方案了。
- YubiKey WordPress Plugin:wordpress登录过程中可使用yubikey配合原密码进行加强安全的登录
- LastPass Login:使用yubikey作为lastpass的master password,详见@ohsc的日志。该功能需lastpass的高级会员权限,每月$1。
- Google Apps:使用yubikey登录Google Apps。要是Gmail也能用yubikey登录,那就nb了
No comments:
Post a Comment