Related
GnuPG only uses keys from your key chain, so it must be in there to use it. How can I force the system to ask the passphrase every time? Old versions of GnuPG uses the gpg-agent, which caches the passphrase for a given time. Use the option -no-use-agent or add a line no-use-agent to /.gnupg/gpg.conf to prevent using the agent.
How To Install and Configure Postfix as a Send-Only SMTP Server on Ubuntu 18.04 Tutorial
How To Set Up and Configure an OpenVPN Server on CentOS 8 Tutorial
Introduction
GPG, or GNU Privacy Guard, is a public key cryptography implementation. This allows for the secure transmission of information between parties and can be used to verify that the origin of a message is genuine.
In this guide, we will discuss how GPG works and how to implement it. We will be using an Ubuntu 16.04 server for this demonstration, but will include instructions for other distributions as well.
How Public Key Encryption Works
A problem that many users face is how to communicate securely and validate the identity of the party they are talking to. Many schemes that attempt to answer this question require, at least at some point, the transfer of a password or other identifying credentials, over an insecure medium.
![Delete gpg key Delete gpg key](/uploads/1/2/5/8/125874477/751327173.png)
Ensure That Only the Intended Party Can Read
To get around this issue, GPG relies on a security concept known as public key encryption. The idea is that you can split the encrypting and decrypting stages of the transmission into two separate pieces. That way, you can freely distribute the encrypting portion, as long as you secure the decrypting portion.
This would allow for a one-way message transfer that can be created and encrypted by anyone, but only be decrypted by the designated user (the one with the private decrypting key). If both of the parties create public/private key pairs and give each other their public encrypting keys, they can both encrypt messages to each other.
So in this scenario, each party has their own private key and the other user’s public key.
Validate the Identity of the Sender
Another benefit of this system is that the sender of a message can “sign” the message with their private key. The public key that the receiver has can be used to verify that the signature is actually being sent by the indicated user.
Set Up GPG Keys
GPG is installed by default in most distributions.
If for any reason GPG is not installed, on Ubuntu and Debian, you can update the local repo index and install it by typing:
On CentOS, you can install GPG by typing:
To begin using GPG to encrypt your communications, you need to create a key pair. You can do this by issuing the following command:
This will take you through a few questions that will configure your keys:
- Please select what kind of key you want: (1) RSA and RSA (default)
- What keysize do you want? 4096
- Key is valid for? 1y (expires after 1 year. If you are just testing, you may want to create a short-lived key the first time by using a number like “3” instead.)
- Is this correct? y
- Real name: your real name here
- Email address: [email protected]
- Comment: Optional comment that will be visible in your signature
- Change (N)ame, ©omment, (E)mail or (O)kay/(Q)uit? O
- Enter passphrase: Enter a secure passphrase here (upper & lower case, digits, symbols)
At this point,
gpg
will generate the keys using entropy. Entropy describes the amount of unpredictability and nondeterminism that exists in a system. GPG needs this entropy to generate a secure set of keys.This process may take a long time depending on how active your system is and the keysize you selected. To generate additional entropy more easily, you can use a tool called haveged. Open up a new terminal and SSH into the server again to set up
haveged
on your server.Create a Revocation Certificate
You need to have a way of invalidating your key pair in case there is a security breach or in case you lose your secret key. There is an easy way of doing this with the GPG software.
This should be done as soon as you make the key pair, not when you need it. This revocation key must be generated ahead of time and kept in a secure, separate location in case your computer is compromised or inoperable. To generate a revocation key, type:
You will be asked to confirm the revocation key creation and then prompted for the reason that it is being revoked. This information will be visible to other users if the revocation is used in the future. You can choose any of the available options, but since this is being done ahead of time, you won’t have the specifics. Often, it is a good idea to create a revocation certificate for each of the likely scenarios for maximum flexibility.
Afterwards, you will then be asked to supply a comment and finally, to confirm the selections. Before creating the revocation certificate, you will need to enter your GPG key’s passphrase to confirm your identity. The revocation certificate will be written to the file specified by the
--output
flag (revocation.crt
in our example):You should immediately restrict the permissions on the generated certificate file in order to prevent unauthorized access:
The revocation certificate must be kept secure so that other users cannot revoke your key. As the message states, you should consider backing the certificate up to other machines and printing it out, as long as you can secure it properly.
How To Import Other Users’ Public Keys
GPG would be pretty useless if you could not accept other public keys from people you wished to communicate with.
You can import someone’s public key in a variety of ways. If you’ve obtained a public key from someone in a text file, GPG can import it with the following command:
There is also the possibility that the person you are wishing to communicate with has uploaded their key to a public key server. These key servers are used to house people’s public keys from all over the world.
A popular key server that syncs its information with a variety of other servers is the MIT public key server. You can search for people by their name or email address by going here in your web browser:
You can also search the key server from within GPG by typing the following:
You can use this method of searching by name or email address. You can import keys that you find by following the prompts.
How To Verify and Sign Keys
While you can freely distribute your generated public key file and people can use this to contact you in a secure way, it is important to be able to trust that the key belongs to who you think it does during the initial public key transmission.
Verify the Other Person’s Identity
How do you know that the person giving you the public key is who they say they are? In some cases, this may be simple. You may be sitting right next to the person with your laptops both open and exchanging keys. This should be a pretty secure way of identifying that you are receiving the correct, legitimate key.
But there are many other circumstances where such personal contact is not possible. You may not know the other party personally, or you may be separated by physical distance. If you never want to communicate over insecure channels, verification of the public key could be problematic.
Luckily, instead of verifying the entire public keys of both parties, you can simply compare the “fingerprint” derived from these keys. This will give you a reasonable assurance that you both are using the same public key information.
You can get the fingerprint of a public key by typing:
This will produce a much more manageable string of numbers to compare. You can compare this string with the person themselves, or with someone else who has access to that person.
Sign Their Key
Signing a key tells your software that you trust the key that you have been provided with and that you have verified that it is associated with the person in question.
To sign a key that you’ve imported, simply type:
When you sign the key, it means you verify that you trust the person is who they claim to be. This can help other people decide whether to trust that person too. If someone trusts you, and they see that you’ve signed this person’s key, they may be more likely to trust their identity too.
You should allow the person whose key you are signing to take advantage of your trusted relationship by sending them back the signed key. You can do this by typing:
You’ll have to type in your passphrase again. Afterwards, their public key, signed by you, will be displayed. Send them this, so that they can benefit from gaining your “stamp of approval” when interacting with others.
When they receive this new, signed key, they can import it, adding the signing information you’ve generated into their GPG database. They can do this by typing:
They can now demonstrate to other people that you trust that their identity is correct.
How To Make Your Public Key Highly Available
Because of the way that public key encryption is designed, there is not anything malicious that can happen if unknown people have your public key.
With this in mind, it may be beneficial to make your public key publicly available. People can then find your information to send you messages securely from your very first interaction.
You can send anyone your public key by requesting it from the GPG system:
You can then send this file to the other party over an appropriate medium.
If you want to publish your key to a key server, you can do it manually through the forms available on most of the server sites.
Another option is to do this through the GPG interface. Look up your key ID by typing:
The highlighted portion in the output below is the key ID (look for the
pub
along the left-hand column if you’re uncertain about which one to use). It is a short way to reference the key to the internal software.To upload your key to a certain key server, you can then use this syntax:
The key will be uploaded to the specified server. Afterwards, it will likely be distributed to other key servers around the world.
Encrypt and Decrypt Messages with GPG
You can easily encrypt and decrypt messages after you have shared your keys with the other party.
Encrypt Messages
You can encrypt messages using the “–encrypt” flag for GPG. The basic syntax would be:
This encrypts the message using the recipient’s public key, signs it with your own private key to guarantee that it is coming from you, and outputs the message in a text format instead of raw bytes. The filename will be the same as the input filename, but with an
.asc
extension.You should include a second “-r” recipient with your own email address if you want to be able to read the encrypted message. This is because the message will be encrypted with each person’s public key, and will only be able to be decrypted with the associated private key.
So if it was only encrypted with the other party’s public key, you would not be able to view the message again, unless you somehow obtained their private key. Adding yourself as a second recipient encrypts the message two separate times, one for each recipient.
Decrypt Messages
When you receive a message, simply call GPG on the message file:
The software will prompt you as necessary.
If instead of a file, you have the message as a raw text stream, you can copy and paste it after typing
gpg
without any arguments. You can press “CTRL-D” to signify the end of the message and GPG will decrypt it for you.Key Maintenance
There are a number of procedures that you may need to use on a regular basis to manage your key database.
To list your available GPG keys that you have from other people, you can issue this command:
Your key information can become outdated if you are relying on information pulled from public key servers. You do not want to be relying on revoked keys, because that would mean you are trusting potentially compromised keys.
You can update the key information by issuing:
This will fetch new information from the key servers.
You can pull information from a specific key server by using:
You may receive error messages if any of your keys cannot be found on the key server.
Conclusion
Using GPG correctly can help you secure your communications with different people. This is extremely helpful, especially when dealing with sensitive information, but also when dealing with regular, everyday messaging.
Because of the way that certain encrypted communications can be flagged by monitoring programs, it is recommended to use encryption for everything, not just “secret” data. That will make it more difficult for people to know when you are sending important data or just sending a friendly hello.
⚠️ Content below I now consider obsolete. My latest guide is now located here: Technical guide for using YubiKey series 4 for GPG and SSH. Please consult that resource instead.
We will generate a master key with only the Certify capability and three subkeys with each of the Sign, Encrypt and Authenticate capabilities. These latter three keys are meant for daily use and will be transferred to an OpenPGP smartcard, which has three corresponding slots. The master private key can then be moved to offline cold storage, or stored on a second smartcard.
![Without Without](/uploads/1/2/5/8/125874477/464081114.png)
We are generating keys on a secure computer instead of on the card, because it allows more flexibility. Ideally this means a machine running Tails or one that is air-gapped and not connected to the internet.
This guide assumes that if you want to sign other peoples keys, then you will require the aforementioned secondary smartcard with your master key stored in its Signature slot, or if you only have one smartcard, then you'll have to fetch the master key out of cold storage. By default, GPG generates a master key with the Certify and Sign capabilities and a subkey with the Encrypt capability. We will override this using expert mode.
First, make sure you're running GnuPG 2.x. This is important because you can't use 4096-bit RSA keys on most smartcards with GnuPG 1.x. A Bash alias will suffice, i.e.
alias gpg=gpg2
.If you use the Enigmail Thunderbird add-on, make sure the GPG path to
/usr/bin/gpg2
.If you're using a YubiKey on Tails, you might need to add udev rules in order to interact with the device. Create a file named
70-yubikey.rules
in /etc/udev/rules.d
with the following contents:Then run
sudo udevadm control --reload-rules
.For the sake of brevity, this guide assumes that you will always enter passphrases and PINs, and answer Yes by typing
y
when prompted.At some point either before or after you should initialize your new smartcard, setting some of the variables if you so choose (stuff like name, url, login, lang, sex), but most importantly modify the default PIN (123456) and admin PIN (12345678). You can do this by running
gpg --card-edit
and typing admin
and then help
to list available commands. Use passwd
to change your PINs. You can also toggle the forcesig
flag to control whether you'd like to require a PIN to be entered every time you sign a message.Generate the master key
Select 8: RSA (set your own capabilities)
Select S, E, and Q so that you're left with only the Certify capability.
Set a 4096 bit key size.
Set the expiration date.
Setup a UID.
Setup a passphrase.
The key is generated.
Add UIDs
Use
gpg> adduid
to add as many UIDs or e-mail addresses as you need. Once you're done, toggle to gpg> uid <#>
and use the gpg> primary
command to set the primary UID.Now we will add subkeys for each capability to be transferred to the main smartcard designated for daily use.
Create the Sign key
Select 4: RSA (sign only).
Set a 4096 bit key size.
Set the expiration date.
The key is generated.
Create the Encrypt key
Select 6: RSA (encrypt only).
Set a 4096 bit key size.
Set the expiration date.
The key is generated.
Create the Authenticate key
Select 8: RSA (set your own capabilities)
Select S and E to toggle off the Sign and Encrypt capabilities.
Select A to toggle on the Authenticate capability and press Q.
Set a 4096 bit key size.
Set the expiration date.
The key is generated.
Set trust level
By the way, you should probably set the public key to the ultimate trust level.
Select 5 = I trust ultimately.
Add signatures
If you want to sign the new master key with your previous key that you're transitioning from, the time is now.
Generate revocation certificate
While you still have access to the master key with the Certify capability, it's a good idea to create a revocation certificate.
Backup everything
You can move these private keys plus the revocation certificate someplace safe, like an encrypted partition or offline storage media.
Transfer your master key to a secondary smartcard
If you have two smartcards available, then you can store your master key in the Signature slot of a second smartcard, and use this one for stuff like signing other peoples keys, and making changes to your key, as in the scheme recommended by Tom Lowenthal's guide. After initializing the card and setting new PINs:
gpg> toggle
gpg> keytocard
Answer 'y' to 'Really move the primary key?'
Select 1: Signature key.
gpg> save
As mentioned, switching to this smartcard will be required whenever you want to sign somebody else's key or make modifications to your key. Now eject it and put it away somewhere. You may want to create a label so you can tell them apart. Insert the primary smartcard that you've selected for daily use.
Load subkeys onto the smartcard
You can use
gpg --card-edit
to initialize your smartcard: set the PINs, and variables like language, sex, your first and last name, or a URL for downloading your key. Now let's load the keys onto it.Select 1: Signature key.
Un-toggle key one:
gpg> key 1
Toggle key two:
gpg> key 2
Select 2: Encryption key.
Un-toggle key two:
gpg> key 2
Toggle key three:
gpg> key 3
Select 3: Authentication key.
Now what?
You shouldn't have to delete any secret keys, as they were moved to the smartcard. When you use either
keytocard
command or perform key generation on the card, GnuPG places a 'stub' in your keyring so that it knows the actual secret key material is located on the smartcard. It looks like you have the secret key on your computer but you actually don't, and you can't decrypt anything without the card. It's just a stub pointing to the smartcard — which is something you do want to keep if you'd like this to be usable.So what if you deleted the secret keys anyway and lost the stubs? Just run
$ gpg --card-status
or open the 'Manage Smartcard' menu in Enigmail in order to instantly re-associate and populate your keyring with the information from your smartcard. However, always keep in mind that you need the corresponding public key in your keyring to work with the smartcard on whatever computer you're using.After you purposely delete the secret key stubs from your keyring (otherwise it will say the keys are already associated with another card), you can even put these same keys on a different smartcard by repeating part of the process above.
However, you should probably backup or transfer these stubs to your regular computer first, since they're pointing to separate smartcards for different subkeys, and it's very difficult to re-create if you lose them—but it can be done using a tool called gpgsplit. Without all of the correct stubs, GnuPG won't prompt you to insert your other smartcard with a different serial number when you try to certify another key or alter attributes.
Transfer this file to your regular, non-airgapped machine and run
gpg --import
. This doesn't contain any actual secret key material — that's been migrated to the smartcard(s). Also make sure you transfer and import a copy of your pubkey.asc
for things to work properly.You now have a working OpenPGP smartcard for use with GPG, Enigmail and more! Now you can let people know about your new key, upload it to keyservers, publish a transition statement, and all of that fun stuff.
Tips
gnome-keyring-daemon has a bad habit of hijacking the GnuPG agent, causing cards and readers to be unrecognized or to behave unpredictably. Many of these issues go away if you disable the ssh & gpg components of gnome-keyring-daemon and let gpg-agent handle them instead. Run gnome-keyring-daemon with only
--components=pkcs11,secrets
...To do this you can
rm /etc/xdg/autostart/gnome-keyring-ssh.desktop
and gnome-keyring-gpg.desktop
or just add Hidden=true
plus X-GNOME-Autostart-enabled=false
to those launchers. If you prefer, you can create a new launcher just for starting gpg-agent (more ideally in ~/.config/autostart
).If you are experiencing 'Card not available' or 'Card error', then you might want to try killing and restarting gpg-agent.
This resolved many issues and my smartcard now works reliably this way on Debian jessie with GnuPG 2.x.
To make sure your smartcard works in every Bash shell you open, it helps to add the following to
~/.bashrc
:This assumes the presence of
write-env-file ~/.gnupg/gpg-agent-info
in your gpg-agent.conf. Evaluating that file helps make sure you have the correct GPG_AGENT_INFO, SSH_AUTH_SOCK and SSH_AGENT_PID environment variables in each terminal session. While we're at it, here's what my ~/.gnupg/gpg-agent.conf
looks like:This configuration depends on two packages you must install via apt-get,
pinentry-qt4
and scdaemon
.One annoying thing about most pinentry applications is that they don't allow pasting from clipboard, making them hard to use with a password manager. If you want to be able to do this, just grab the latest source of pinentry-qt4 (0.8.4 or greater) and then compile it with this option:
./configure --enable-pinentry-qt4-clipboard=yes
.Using the smartcard key for SSH authentication
You can use your 4096-bit Authenticate key on the smartcard with SSH. This has the advantage that you can't log in to any servers without possession of the device. It's easiest to do with the latest GnuPG 2.1.x, otherwise you may have to install monkeysphere and use the
openpgp2ssh
tool, which we're going to skip. Note: this won't work unless you've set a non-default smartcard PIN of at least 6 digits.On GnuPG 2.0.x, when you run gpg-agent with
enable-ssh-support
so that it takes over for ssh-agent, your smartcard's Authenticate subkey should automatically be recognized as a valid SSH key and become available for the SSH client to use as an identity. But you might have trouble getting it to work, so here are some extra steps which can assist the process:Add
enable-ssh-support
and write-env-file
to ~/.gnupg/gpg-agent.conf
Fetch the keygrip of your master public key with
gpg2 --with-keygrip -k
and add these 40 hex digits as a line to~/.gnupg/sshcontrol
.Make sure
gpg-agent --daemon --options ~/.gnupg/gpg-agent.conf
is running in the background. If you run ssh-add -l
it should list an SSH identity corresponding to the RSA key on your smartcard.Check
echo $SSH_AUTH_SOCK
- it should be pointing to gpg-agent's socket instead of ssh-agent. If it's not you have to kill ssh-agent or make sure it doesn't start.Get the 16-digit long ID of your Authenticate subkey and feed it into
gpgkey2ssh
:You can add the contents of ssh_id.pub to
~/.ssh/authorized_keys
on any system you like, or you can try ssh-copy-id
.Now your SSH agent should be communicating with gpg-agent and the RSA Authenticate key on your smartcard is a valid SSH identity. When you run SSH with your smartcard connected, it will automatically attempt to authenticate using it.
More resources:
How to obtain the OpenPGP smartcards and USB readers
Gpg Generate Key Without Prompt Windows 10
I now recommend the YubiKey version 4 instead of the OpenPGP smartcard from g10 code. It's modern hardware, much faster, and has many great features. These devices can be purchased from Amazon.
Gpg Generate Key Without Prompt Password
If you have any questions about the information in this guide, you can reach me on Twitter @ageis, by e-mail to kevin [at] freedom [dot] press (PGP key), or XMPP/Jabber: [email protected].