Skip to content

Расширенная настройка Yubikey и GPG

Первоначальная настройка Yibikey

Настройка FIDO

ykman info
ykman fido info
ykman fido access change-pin

Настройка PIV

ykman piv access change-pin
ykman piv access change-puk
ykman piv access change-management-key --generate
copy key

Save Master Secret Key to Yubikey PIV slot 0x5fc109 (Printed Information) require PIN:

pbpaste | ykman piv objects import --management-key ______________________________ 0x5fc109 -
ykman piv objects export 0x5fc109 -

Настройка OTP

Generate key Challenge-response with Require touch in Slot 1

ykman otp chalresp -t -g  1

Настройка GPG

Сбросим GPG: ykman openpgp reset

Изменим PIN codes (default PIN 123456, Admin PIN 12345678):

gpg --card-status
gpg --change-pin
    1 - change PIN
    3 - change Admin PIN
    4 - set the Reset Code

# 3 0 3 - is default
ykman openpgp access set-retries 3 3 3

Установим чтобы требовал touch при каждой операции с ключом

ykman openpgp keys set-touch aut on
ykman openpgp keys set-touch sig on
ykman openpgp keys set-touch enc on

Персональная настройка GPG на Yubikey

gpg --card-edit
    > admin
        name Volodin
            given name Aleks
        sex M
        lang en
        login voale
        url https://github.com/4volodin.gpg
        key-attr
            1, 4096
            1, 4096
            1, 4096
Основные этапы, которые мы собираемся настроить:

  • Мастер-ключ длиной 4096 бит, который будет храниться в офлайн-режиме.
  • Сертификат отзыва (revocation certificate), который также будет храниться в офлайн-режиме.
  • Подключение суб-ключей длиной 4096 бит для шифрования, подписи и аутентификации.
  • Публикация ключей в Keybase и других каталогах.
  • Автоматическая подпись коммитов Git с помощью ключа GPG.
  • Настройка gpg-agent для работы в качестве ssh-agent для удаленного доступа.

Generate keys

By Default Yubikey creates 1 Master key (SC) + SUB Encryption(E) + Sub Auth (A)

Choose 1 or 2

1. Ручная генерация GPG ключей
// Generate Master Key (SC)
gpg --expert --full-generate-key
    8 S E  Q 4096 0 y
    voale
    4volodin@gmail.com

// Generate SubKey Encryption - 1year
gpg --expert --edit-key voale
    addkey 8 (only sign and encrypt) 4096 1y

// Generate SubKey Auth - 1year
gpg --expert --edit-key voale
    addkey 8 S E A (only Auth) Q 4096 1y

gpg> save

2. Автоматическая генерация GPG ключей

../gpg-keygen

gpg -K

//if you haven't keys -> you should import keys
gpg --import gpg-$NAME-master-secret-key+subs.gpg

gpg --edit-key voale trust
5 Trust ultimately
gpgreload

Transfer keys to Yubikey

1-ый yubikey для S,E,A - SubKeys,

2-ой yubikey для C -MasterKey

There are only 3 available slots for gpg certificates on Yubikey

gpg --edit-key 4volodin
    key 1 - SA key to auth slot
    keytocard
    3 - Auth slot

    key 1
    key 2 - Encr Subkey to -> Encryption slot on YubiKey
    keytocard

    key 2
    quit  WITHOUT SAVING!!!!! This will leave the keys on the Yubikey but NOT change the  GPG keyring to point to the Yubikey1 with a stub


    Insert Yubikey2

gpg --edit-key 4volodin KEY_ID_in_longform_without_0x
    key 1 - SA key to auth slot
    keytocard
    3 - Auth slot

    key 1
    key 2 - Encr Subkey to -> Encryption slot on YubiKey
    keytocard

    key 2

    //without selecting keys - move Primary Master key to Signature slot
    keytocard

    save

GO TO **_for SSH auth_**

SSH auth

1. fot Github.com
    It is not necessary to import the corresponding GPG public key in order to use SSH. Copy and paste the output from ssh-add -L to the server’s authorized_keys file. Extract the public key from the SSH agent

In the case of YubiKey usage, to extract the public key from the ssh agent:

$ ssh-add -L | grep "cardno:" >> ssh-$NAME-public-key-opengpg.txt ~/.ssh/id_rsa_yubikey.pub
Then you can explicitly associate this YubiKey-stored key for used with a host, github.com for example, as follows:

$ cat << EOF >> ~/.ssh/config
Host github.com
    IdentitiesOnly yes
    IdentityFile ~/.ssh/id_rsa_yubikey.pub
EOF

2. for ssh server

    ssh-add -L | grep "cardno:" | ssh remote_username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

    echo $KEY_GRIP_AUTH >> ~/.gnupg/sshcontrol

Git code signing

Use a Yibikey to sign commits and tags, It can also be used for SSH authentication, allowing you to push, pull, and commit without a password.

git config --global user.name ""
git config --global user.e.mail ""
Make sure the user.email option matches the e-mail address associated with the PGP identity.

SERVER Configuration:

To enable code signing with Git + Github:
gpg -k
sub   ed25519/0x9B76AA52AF00EFEF 2020-10-11 [S] [expires: 2021-10-11]

The subkey that interests us is the one to sign ([S]). Grab its ID and export it.
gpg --armor --export 0x9B76AA52AF00EFEF

Upload the output of gpg --export --armor 0x9580281E3F08A7D9 (your GPG public keys) to https://github.com/settings/keys.
Tell git which key to use: git config --global user.signingkey 0x9B76AA52AF00EFEF
Tell git to sign always commits: git config --global commit.gpgsign true
Tell git to sign always tags: git config --global tag.gpgSign true

git log --show-signature

CLIENT Configuration:
gpg -K
The subkey that interests us is the one to sign ([S]). Copy its ID.
Now give some information to git.
Enable GPG program
    git config --global gpg.program gpg
Link the subkey
Paste the subkey ID.
    git config --global user.signingkey 0x9B76AA52AF00EFEF
Enable signing for all commits
This feature is optional. If you don’t want to sign every commit, you can also do it with the -S flag in the git commit command.
    git config --global commit.gpgsign true

Forwarding GPG key

//check OpenSSH version >= 6.7 ssh -V

  1. Find out where the agent socket is on the remote system:

    $ gpgconf --list-dirs agent-socket /run/user/1000/gnupg/S.gpg-agent

  2. Find out where the extra socket of the GPG agent is on your local system:

    $ gpgconf --list-dirs agent-extra-socket /run/user/1000/gnupg/S.gpg-agent.extra

  3. Edit the SSH configuration in ~/.ssh/config on the local machine to forward the socket to the remote machine:

    Host rasp RemoteForward

  4. The public key suitable for the YubiKey must also be present on the target system. For simplicity, we can copy the local collection of public keys to the remote machine:

    scp ~/.gnupg/pubring.kbx rasp:~/.gnupg/ gpg --export-ownertrust | ssh remote.host gpg --import-ownertrust

    OR

    gpg --export-options export-local-sigs --export $EMAIL | ssh remote.host gpg --import gpg --export-ownertrust | ssh remote.host gpg --import-ownertrust

  5. Add the following configuration parameter to your SSH server configuration (/etc/ssh/sshd_config):

    StreamLocalBindUnlink yes

Now log out and log back in. From now on it should be possible to create signatures etc. with the private key of the YubiKey.

Also, problems may occur if the gnupg versions are different between local and remote machines. Therefore you should check that the versions are the same or at least not too different.

Операции с GPG ключами

Добавить дополнительные gpg ключи

gpg --list-secret-keys --with-keygrip Add to ~/.gnupg/sshcontrol with the Authentication "keygrip"; this allows the gpg-agent to use this key with SSH.

Удалить Master Key and Subs ключи

    1. Delete Private Master Key Using export-delete-import method
gpg --export-secret_subkeys -a KEY_ID_in_longform_without_0x > secret_subs.gpg
gpg --delete-secret_keys KEY_ID_in_longform_without_0x
gpg --import secret_subs.gpg


    2. Delete Private Master key and other Using OneByOne method

gpg -K --with-keygrip
gpg-connect-agent "DELETE_KEY 5436620CA40373692E45B41A7831BEC2ACE624AB" /bye
        # and then delete Public or Private Sub keys
gpg --expert --edit-key KEY_ID_in_longform_without_0x
key NUMBER
delkey

# Get help how to delete key
gpg-connect-agent 'help delete_key' /bye
        # DELETE_KEY [--force|--stub-only] <hexstring_with_keygrip>

    3. Delete only private keys по очереди начиная с мастер ключа, если процедуру прервали то дальше удаляться не будут ключи, только то что уже удалили
gpg --delete-secret-keys KEY_ID_in_longform_without_0x
        # and then delete Public Sub key
gpg --delete-keys KEY_ID_in_longform_without_0x

You can verify that it has been deleted by listing the private keys again -- the master key should have a # next to it to signify that it cannot be used (the > next to the subkeys means that they are on the YubiKey

Import Master key from Paper

paperkey --pubring paper-public-key.txt.gpg --secrets paper-secret-key.txt | gpg --import

Renew sub-keys

Renewing subkeys is simple: 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 have 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.

//if you have key which is stubs to yubikey you need delete stubs using
gpg-connect-agent "DELETE_KEY --stub-only 5436620CA40373692E45B41A7831BEC2ACE624AB" /bye
the same for Sub-stubs
and then import master key or subkeys

gpg --import master.key
# select all subkeys and renew them
gpg --edit-key voale
    key 1
    key 2
    key 3
    expire
    1y
    save
# удалить всю секретную часть ключа, удалит и мастер и сабключи разом
gpg --delete-secret-key MYKEYID
gpgreload
gpg --export voale > pubkey.gpg
save pubkeys on USB flash

#Transfer that public key to the computer from which you use your GPG key, and then import it with.
# Import the new public keys exported as a part of the master key export process
gpg --import pubkey.gpg


// so now you can update the pub key that stored on the various keyservers. To archieve this use the following command
gpg --keyserver pgp.mit.edu --send-keys key-ID

#This will extend the validity of your GPG key and will allow you to use it for SSH authorization. Note that you do not need to update the SSH public key located on remote servers.
#don't need to update the SSH public key

Revocate key and notificate public server

gpg --list-key

// revoke key
gpg --output revoke.asc --gen-revoke key-ID

// import revocation certificate into my keyring
gpg --import revoke.asc
// after import program have to show the key as revocated and then you have to public revocated key to public server key

// search my key on public keys server
gpg --keyserver pgp.mit.edu --search-keys key-ID

// send revocated key to public server keys
gpg --keyserver pgp.mit.edu --send-keys key-ID

// get key from public server
gpg --keyserver pgp.mit.edu --recv-keys <KeyID>

How to know private-keys-v1.d files

Remove Yubikey 1, then enter the edit-key menu of the key you just moved. Use the 'grip' command to find the Keygrips of each key. You will find a .key file for each keygrip in your ~/.gnupg/private-keys-v1.d/* folder... delete them, while being careful not to delete anything else (don't want to wipe private keys for unrelated rings)

How to know grip keys
gpg --edit-key voale
grip

~/.gnupg/private-keys-v1.d/$KEYGRIP.key

Создать доверие для GPG ключа

// Теперь надо выдать доверие новому ключу, поскольку мы лишили его родителя и, следовательно, цепь доверия разорвалась.
gpg --edit-key voale trust
5 Trust ultimately

Verify Github

curl https://github.com/web-flow.gpg | gpg --import
gpg --edit-key noreply@github.com
    trust
    4
gpg --lsign-key noreply@github.com

Как верифицировать чужие signed commits

$ git log --show-signature

commit 1bd20e9f7ed0860dc1971957b61ea25aeea499a1
gpg: Signature made Tue  6 Feb 00:04:43 2018 AEDT
gpg:                using RSA key 4AEE18F83AFDEB23
gpg: Can't check signature: No public key
Merge: c1218d5 0dde09c
Author: Brendan Roy <br3ndanr@gmail.com>
Date:   Tue Feb 6 00:04:43 2018 +1100

    Merge pull request #1 from bmon/pullreq

    this is a test

curl 'https://sks-keyservers.net/pks/lookup?op=get&search=0x4AEE18F83AFDEB23' | gpg --import

or

gpg --keyserver hkp://pgp.mit.edu --search-keys 0x4AEE18F83AFDEB23

Операции с Yubikey

Переключение на второй Yubikey

# To switch to Yubikey1 at any time run this script to force GPG
# to repoint the key stubs to the inserted Yubikey

his will leave you with two Yubikeys with identical subkeys.
However, GPG will have deleted the actual keys in step 4 above and replaced them with key stubs pointing to Yubikey2
To use Yubikey1 you need to force GPG to repoint the stubs to the new card...

because GPG keys related with certain Yubikey serialno
you shoult switch yubi:
    read -p "Insert the Yubikey you want to use ....  "   ignore
    echo "Switching GPG to backup Yubikey ..."
    gpg-connect-agent "scd serialno" "learn --force" /bye
or
    #!/usr/bin/env bash
    keyid=YOUR_KEY_ID_GOES_HERE
    gpgconf --kill gpg-agent
    cd "$(gpgconf --list-dirs homedir)/private-keys-v1.d"
    gpg -K --with-keygrip --with-colons "$keyid" | \
    awk -F: '/^grp/ { print $10".key"; }' | \
    xargs rm -vf

Использование GPG key на чужом ПК

Вставьте Yubikey и через комануд fetch закачайте публичные ключи в gpg и выдайте trust 5.

gpg --card-edit
fetch
quit
gpg --edit-key KEY_ID
trust
5
quit

Как сбросить PIN на Yubikey после блокировки

При использовании Yubikey в качестве GPG, ввод неправильного PIN-кода несколько раз приведет к блокировке. Вы можете разблокировать Yubikey, используя административный PIN-код.

$ gpg --edit-card
gpg/card> admin
Admin commands are allowed

gpg/card> passwd
gpg: OpenPGP card no. D2760001240102010006096610530000 detected

1 - change PIN
2 - unblock PIN
3 - change Admin PIN
4 - set the Reset Code
Q - quit

Your selection? 2

Необходимо ввести admin pin, а затем установить новый PIN

В завершениe

Убедитесь, что вы:

  • сохранили подключенные к YubiKey ключи шифрования, подписи и аутентификации (команда gpg -K должна показать ssb> для подключей),
  • cохраните пользовательский и административный PIN-коды YubiKey, которые вы изменили из значений по умолчанию,
  • cохраните пароль к основному ключу GPG
  • cохраните копию основного ключа, подключей и сертификата аннулирования на зашифрованном носителе, который будет храниться оффлайн,
  • cохраните пароль к этому зашифрованному носителю в отдельном месте,
  • cохраните копию открытого ключа в удобном месте для последующего доступа.