Traduções: English - Français - Italiano - Português (Brasil)


Usando subchaves OpenPGP no desenvolvimento do Debian

O que são chaves?

Em criptografia de chave pública, uma chave é na verdade um par: uma chave pública e uma chave privada. Você usa a chave privada para assinar arquivos digitalmente e outras pessoas usam a chave pública para verificar a assinatura. Ou, outra pessoas usam a chave pública para criptografar algo e você usa a chave privada para descriptografar.

Enquanto somente você tiver acesso à chave privada, outras pessoas podem confiar que suas assinaturas estão sendo feitas por você, e você pode confiar que ninguém mais é capaz de ler as mensagens criptografadas por você.

O GnuPG, a implementação usada no Debian, seleciona a chave correta em qualquer ocasião necessária.

O que são subchaves?

O OpenPGP também suporta subchaves, que são como chaves normais, mas que estão vinculadas a um par de chaves primárias. Uma subchave pode ser usada para assinar ou para criptografar. A parte realmente útil de subchaves é que podem ser revogadas independentemente das chaves primárias e também podem ser armazenadas separadamente.

Em outras palavras, subchaves são como um par de chaves em separado, mas automaticamente associadas com seu par de chaves primárias.

Na verdade, o GnuPG usa uma chave exclusiva de assinatura como chave primária e cria uma subchave de criptografia automaticamente. Sem uma subchave para criptografia, você não conseguiria criptografar e-mails com o GnuPG. O Debian requer que você tenha a subchave de criptografia para que certas coisas possam ser enviadas por e-mail para você com segurança, como a senha inicial para sua conta shell debian.org.

Por quê?

Subchaves tornam a administração de chaves mais fácil. O par de chaves primária é muito importante: é a melhor prova de sua identidade on-line, aos menos para o Debian, e se você perdê-las, terá que reconstruir sua reputação do zero. Se alguém mais obtiver acesso à sua chave primária privada ou à sua subchave privada, é possível fazer com que todas as pessoas acreditem que é você: pode-se fazer o upload de pacotes em seu nome, votar em seu nome, e fazer qualquer coisa que você faria. Isto pode ser muito danoso para o Debian. Isso vai dar muita dor de cabeça. Então você deve manter suas chaves privadas bem guardadas.

Você deve manter sua chave primária privada muito, muito bem guardada. Contudo, manter todas as suas chaves em extrema segurança é inconveniente: toda vez que precisar assinar um novo upload de pacote você precisará copiar os pacotes para uma mídia portável adequada, ir até o subsolo, provar para a guarda armada que você é você usando diversos métodos biométricos e outras formas de identificação, passar por um labirinto mortal, alimentar os cães de guarda com o tipo correto de carne, e finalmente abrir o cofre, pegar o notebook de assinatura e assinar os pacotes. Aí fazer o inverso para conseguir a conexão com a Internet para realizar o upload dos pacotes.

As subchaves deixam isso mais fácil: você já tem uma subchave de criptografia criada automaticamente e você cria uma outra subchave para assinatura, e as mantém em seu computador principal. Você divulga as subchaves em servidores normais de chaves e qualquer pessoa pode usá-las em vez das chaves primárias para criptografar mensagens ou para verificar suas assinaturas de mensagens. Da mesma forma, você usará as subchaves para descriptografar e assinar mensagens.

Você precisará usar as chaves primárias somente em circunstâncias excepcionais, particularmente quando quiser modificar suas próprias chaves ou de outras pessoas. Mais especificamente, você precisará de sua chave privada primária:

(Porque cada uma dessas operações é realizada ao se adicionar uma nova assinatura própria/de revogação de uma chave primária privada).

Como cada ligação da Rede de Confiança (Web of Trust) é um endosso do vínculo entre uma chave pública e um ID de usuário(a), as assinaturas de certificação OpenPGP (da chave primária privada de quem assina) são relativas ao UID e são irrelevantes para as subchaves. Em particular, a criação ou revogação de subchaves não afetam a reputação da chave primária. Assim, no caso em que sua subchave for roubada enquanto sua chave primária permanece segura, você pode revogar a subchave comprometida e substitui-la com uma nova subchave sem ter que reconstruir sua reputação e sem reduzir a reputação de chaves assinadas de outras pessoas com sua chave privada.

How?

Unfortunately, GnuPG's user interface is not entirely fun to use. We'll take you through the necessary steps below.

These instructions assume you use one computer, and keep the primary keys on an encrypted USB flash drive, or preferably at least two (you should keep backups of your secret keys). We also assume you already have a key; if not, see http://keyring.debian.org/creating-key.html for instructions.

  1. Make backups of your existing GnuPG files ($HOME/.gnupg). Keep them safe. If something goes wrong during the following steps, you may need this to return to a known good place.

    • umask 077; tar -cf $HOME/gnupg-backup.tar -C $HOME .gnupg

    (note: umask 077 will result in restrictive permissions for the backup.)
  2. Create a new subkey for signing.
    • Find your key ID: gpg --list-keys yourname

    • gpg --edit-key YOURPRIMARYKEYID

    • At the gpg> prompt: addkey

    • This asks for your passphrase, type it in.
    • Choose the "RSA (sign only)" key type.
    • It would be wise to choose 4096 (or at least 2048) bit key size.
    • Choose an expiry date (you can rotate your subkeys more frequently than the primary keys, or keep them for the life of the primary key, with no expiry).
      • Julian calendars can help calculate the exact number of days to a target calendar date

      • date +%j # command line to display current Julian date

      • date -d 2021-05-16 +%j # command to display specific Julian date

    • GnuPG will (eventually) create a key, but you may have to wait for it to get enough entropy to do so.
    • Save the key: save

  3. You can repeat this, and create an "RSA (encrypt only)" subkey as well, if you like or if you need to. As mentioned above, keep in mind that the default option when initially creating a new keypair is to create an encryption subkey, so you probably have one already. In any case, for Debian, just the signing key is sufficient.
  4. Now copy $HOME/.gnupg to your USB drives.

  5. Here comes the tricky part: you need to remove the private primary key.
    • If you are using GnuPG 2.1 or later, all you have to do is to delete the file $HOME/.gnupg/private-keys-v1.d/KEYGRIP.key, where KEYGRIP is the "keygrip" of the primary key which can be found by running gpg2 --with-keygrip --list-key YOURPRIMARYKEYID. (The private part of each key pair has a keygrip, hence this command lists one keygrip for the primary key and one for each subkey.) Note however that if the keyring has just been migrated to the new format, then the now obsolete $HOME/.gnupg/secring.gpg file might still contain the private primary key: thus be sure to delete that file too if it is not empty.

    • Unfortunately GnuPG <2.1 does not provide a convenient way to do remove the private primary key. Instead, we need to export the subkey, remove the private key, and import the subkey back.

      • Export the subkeys: gpg --output secret-subkeys --export-secret-subkeys YOURPRIMARYKEYID. Alternatively, specify the subkey IDs each followed with an exclamation mark to choose which subkeys to export: gpg --output secret-subkeys --export-secret-subkeys SUBKEYID! [SUBKEYID! ..]

      • Remove your primary secret key: gpg --delete-secret-keys YOURPRIMARYKEYID

      • Import the subkeys back: gpg --import secret-subkeys

      • Remove the file containing the private subkeys: rm secret-subkeys

    Verify that gpg -K shows a sec# instead of just sec for your private key. That means the secret key is not really there. (See the also the presence of a dummy OpenPGP packet in the output of gpg --export-secret-keys YOURPRIMARYKEYID | gpg --list-packets.)

  6. Change the passphrase protecting the subkeys: gpg --edit-key YOURPRIMARYKEYID passwd. This way if your everyday passphrase is compromised, the private primary key will remain safe from someone with access to the backup: the private key material on the backup, including the private primary key, are protected by the old passphrase.

Your computer is now ready for normal use.

When you need to use the primary keys, mount the encrypted USB drive, and set the GNUPGHOME environment variable:

export GNUPGHOME=/media/something
gpg -K

or use the --homedir command-line argument:

gpg --homedir=/media/something -K

The latter command should now list your private key with sec and not sec#.

Then what?

At this point, you have a subkey, and you need to send it to the Debian keyserver, if your key is already in the Debian keyring, and the general keyserver network:

gpg --keyserver hkp://keyring.debian.org --send-key YOURPRIMARYKEYID
gpg --keyserver hkp://pool.sks-keyservers.net --send-key YOURPRIMARYKEYID

The upload to the Debian key server only works if your primary public key is in the DD or DM keyrings already: the Debian key server accepts updates to existing keys, but not new keys. New keys are added by the keyring maintainers manually. Updates to keys further need a manual update to be added to the actual keyring used by Debian's servers, which usually happens about once a month. (See https://salsa.debian.org/debian-keyring/keyring/commits/master to see if your subkey has been added.)

So it may take 1 month, to make the new ?SubKeys get updated to Debian online servers.

(First time your key gets added to the Debian keyrings: manual, when you get accepted as DD or DM. After that, uploading subkeys to key server: automatic. Copying updates from key server to the Debian keyrings: manual, once a month.)

After this, you should be able to upload packages to Debian using the subkey, rather than the primary key. The subkey will inherit the web-of-trust status of the primary key pair.

Eeek

If disaster strikes, and you need to revoke the subkey for whatever reason, do the following:

  1. Mount the encrypted USB drive.
  2. export GNUPGHOME=/media/yourdrive

  3. gpg --edit-key YOURPRIMARYKEYID

  4. At the gpg> prompt, list the keys (list), select the unwanted one (key 123), and generate a revocation certificate (revkey), then save.

  5. Send the updated key to the keyservers as above.

Caveats

Multiple Subkeys per Machine vs. One Single Subkey for All Machines

One might be tempted to have one subkey per machine so that you only need to exchange the potentially compromised subkey of that machine. In case of a single subkey used on all machines, it needs to be exchanged on all machines in case of a compromising.

But this only works for signing subkeys. If you have multiple encryption subkeys, gpg is said to encrypt only for the most recent encryption subkey and not for all known and not revoked encryption subkeys.