Skip to content

Instantly share code, notes, and snippets.

@tonybolzan
Last active Jan 17, 2022
Embed
What would you like to do?
Ubuntu 20.04 + GPG | Git, SSH, Yubikey 5
#!/bin/bash
#
# Ubuntu 20.04 + GPG | Git, SSH, Yubikey 5
#
# https://github.com/dainnilsson/scripts/blob/master/base-install/git.sh
# https://github.com/dainnilsson/scripts/blob/master/base-install/gpg.sh
# https://riseup.net/en/security/message-security/openpgp/best-practices
# https://www.forgesi.net/gpg-smartcard/
############################################################
## Instalação de dependências e configuração
############################################################
sudo add-apt-repository ppa:yubico/stable
sudo apt-get update
sudo apt-get install gnupg2 pcscd scdaemon qrencode yubikey-personalization yubikey-manager
# Se você nunca usou GPG, você pode remover suas configs e seu banco padrão para iniciar do zero
rm -rf ~/.gnupg
# Garanta que o diretório exista ~/.gnupg
gpg2 --list-keys
# Configurar para o gpg usar as melhores praticas de segurança
cat >> ~/.gnupg/gpg.conf <<EOF
no-emit-version
no-comments
keyid-format 0xlong
with-fingerprint
use-agent
personal-cipher-preferences AES256 AES192 AES CAST5
personal-digest-preferences SHA512 SHA384 SHA256 SHA224
cert-digest-algo SHA512
default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed
keyserver hkp://keyserver.ubuntu.com
EOF
# Configurar gpg-agent para suportar ssh
echo "enable-ssh-support" >> ~/.gnupg/gpg-agent.conf
# Reiniciar o agente
gpg-connect-agent killagent /bye
gpg-connect-agent /bye
gpgconf --launch gpg-agent
# Incluir as configurações no ~/.bashrc para o SSH e o GPG conversarem
echo 'export GPG_TTY="$(tty)"' >> ~/.bashrc
echo 'export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)' >> ~/.bashrc
# Validatar a conexão com o gpg-agent. Saída = The agent has no identities.
ssh-add -L
############################################################
## GPG - Gerando uma nova chave
############################################################
export USERID='Tonin Bolzan <tonin@bolzan.io>'
# Criar a chave master (Será solicitada para criar uma senha para esta chave)
gpg2 --quick-gen-key "${USERID}" rsa4096 cert 0
# Extrair fingerprint da chave publica e privada
export KEYPUB=$(gpg2 --list-keys --with-colons "${USERID}" | awk -F: '/^pub:/ { print $5;exit; }')
export KEYPRI=$(gpg2 --list-keys --with-colons "${USERID}" | awk -F: '/^fpr:/ { print $10;exit; }')
# Criar as subchaves com expiração de 2 anos (Será solicitada a sua senha)
gpg2 --quick-add-key ${KEYPRI} rsa4096 sign 2y
gpg2 --quick-add-key ${KEYPRI} rsa4096 auth 2y
gpg2 --quick-add-key ${KEYPRI} rsa4096 encr 2y
# Mostrar as chaves que foram geradas
gpg2 --list-keys
# Backup das chaves privadas em um lugar seguro, como um pen-drive velho
cd /media/${USER}/gpg/
tar -czf gnupg.tgz ~/.gnupg
gpg2 --armor --export ${KEYPRI} > public-key.asc
gpg2 --armor --export-secret-key ${KEYPRI} > secret-key.asc
gpg2 --armor --export-secret-subkeys ${KEYPRI} > secret-subkey.asc
# Backup em QRCODE
gpg2 --armor --export-secret-key ${KEYPRI} | qrencode -t PNG -Sv40 -o secret-key.png
# Checksum
sha512sum *.{tgz,asc,png} > gnupg.sha512
# Upload da chave publica para servidores compartilhados
keybase pgp update
gpg2 --keyserver hkp://keyring.debian.org --send-key ${KEYPUB}
gpg2 --keyserver hkp://keyserver.ubuntu.com --send-key ${KEYPUB}
############################################################
## GIT - Assinar seus commits automaticamente
############################################################
git config --global user.signingkey ${KEYPUB}
git config --global commit.gpgsign true
git config --global gpg.program gpg2
git config --global core.sshCommand "SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket) ssh "
############################################################
## Yubikey - Colocar a chave no card
############################################################
# Plugar o Yubikey na usb
gpg2 --card-status
# Alterar as senhas padrões: PIN 123456 e Admin PIN 12345678
gpg2 --card-edit
#> admin
#> passwd
#> 1
#> (digitar PIN atual + novo + confirmação)
#> 3
#> (digitar Admin PIN atual + novo + confirmação)
#> q
#> name
#> (digitar sobrenome)
#> (digitar 1º nome)
#> login
#> (digitar username)
#> lang
#> (pt)
#> sex
#> (M)
#> url
#> (http://keybase.io/bolzan/key.asc)
#> quit
# Enviar chave para o Yubikey
gpg2 --expert --edit-key ${KEYPRI}
#> (Procure a entrada ssb com uso: S, se for a primeira digite key 1)
#> key 1 (para selecionar)
#> keytocard
#> (Selecione Assinatura da chave)
#> (Digite a senha da chave e depois o Admin PIN)
#> key 1 (para deselecionar)
#>
#> (Procure a entrada ssb com uso: A, se for a segunda digite key 2)
#> key 2 (para selecionar)
#> keytocard
#> (Selecione Autenticação da chave)
#> (Digite a senha da chave e depois o Admin PIN)
#> key 2 (para deselecionar)
#>
#> (Procure a entrada ssb com uso: E, se for a terceira digite key 3)
#> key 3 (para selecionar)
#> keytocard
#> (Selecione Encripitação da chave)
#> (Digite a senha da chave e depois o Admin PIN)
#> key 3 (para deselecionar)
#>
#> save
# Remova a chave primária do sistema
gpg2 --delete-secret-keys ${KEYPRI}
# Ativar YubiKey touch (opcional)
ykman openpgp touch aut on
ykman openpgp touch sig on
ykman openpgp touch enc on
############################################################
## Yubikey - Usar em Outros computadores
############################################################
# Plugar o Yubikey na usb
gpg2 --card-edit
#> fetch
#> quit
gpg2 --edit-key tonin@bolzan.io
#> trust
#> (5 = Eu confio ao extremo)
#> quit
############################################################
## Testando se tudo está ok
############################################################
# Desplugue o Yubikey
touch /tmp/test.txt
gpg -e -r tonin@bolzan.io /tmp/test.txt
gpg -d /tmp/test.txt.gpg
# Deve dar erro
# Plugue o Yubikey
gpg -d /tmp/test.txt.gpg
# Deve pedir o PIN
# Desplugue o Yubikey
ssh-add -L
# deve apresentar "The agent has no identities."
# Plugue o Yubikey
ssh-add -L
# deve apresentar sua chave publica SSH
############################################################
## GIT - Configurando GitHub, GitLab
############################################################
# Copie sua chave pública
gpg2 -a --export tonin@bolzan.io
# https://github.com/settings/gpg/new
# https://gitlab.com/profile/gpg_keys
# Cole e salve
# PS.: Bitbucket Cloud não suporta GPG
############################################################
## SSH - Configurando Servidor Remoto
############################################################
# Plugue o Yubikey
ssh-add -L
# Copie o código que possui no final cardno:* do Yubikey inserido atualmente
# copie para o seu servidor normalmente
ssh-copy-id root@192.168.1.10
############################################################
## Extender o tempo de vida da chave
############################################################
# Desconecte o Yubikey da USB
export GNUPGHOME=$(mktemp -d /tmp/gpg_XXXXX)
cp ~/.gnupg/gpg.conf "$GNUPGHOME/gpg.conf"
gpg2 --list-keys
gpg2 --import secret-key.asc # Digitar a senha
gpg2 --list-secret-keys # Verificar se é [final]
export USERID='Tonin Bolzan <tonin@bolzan.io>'
export KEYPUB=$(gpg2 --list-keys --with-colons "${USERID}" | awk -F: '/^pub:/ { print $5;exit; }')
export KEYPRI=$(gpg2 --list-keys --with-colons "${USERID}" | awk -F: '/^fpr:/ { print $10;exit; }')
gpg2 --expert --edit-key "$KEYPRI"
#> # (Selecione todas as entradas ssb com validade expirando)
#> key 1 (para selecionar 1)
#> key 2 (para selecionar 2)
#> key 3 (para selecionar 3)
#> expire
#> # Are you sure you want to change the expiration time for multiple subkeys? y
#> # A chave é valida por? (0) 1y
#> # Está correto (s/N)? s
#> save
# Repita o processo "Upload da chave publica para servidores compartilhados"
# Conectar o Yubikey na USB
gpg2 --expert --edit-key ${KEYPRI}
#> Repita o processo "Enviar chave para o Yubikey"
# Limpeza
rm -rf "$GNUPGHOME"
unset GNUPGHOME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment