92

Setting up keys for a local repository on a new ubuntu 20.10 virtual machine, I got a message that apt-key add was deprecated and I should read the apt-key(8) man page. The apt-key(8) man page is a collection of words strung together, but if it contains information I can't winkle it out. Can anyone tell me what, exactly, I should type on my terminal instead of:

apt-key add name-of-file

The command does apparently still work after honking at me, so I was able to proceed, but would like to know what I'll need to do in the future.

1
  • 1
    Meta question: This is only about adding key files. What about all of the instructions around the Internet that ask you to add keys based on key ID? It's related to the question title, but not the body. Should we ask a separate question or edit this question?
    – Cliff
    Dec 7, 2020 at 19:19

7 Answers 7

142

You need to know why apt-key add is deprecated

All of the answers so far work around the symptom ("Don't use apt-key add") but fail to address the actual problem that led to apt-key add being deprecated. The problem is not a question of appending a key to one big keyring file etc/apt/trusted.gpg vs manually putting single-key keyring files into the directory /etc/apt/trusted.gpg.d/. These two things are equivalent, and doing either one is a huge security risk.

The problem is that any key you add to either of the above is completely and unconditionally trusted by apt. This means that when installing any package from any repo (including the official distro repos), apt will happily accept the package being signed by any of those trusted keys (whether the key belongs to the repository the package is coming from or not). This weakens the assurance provided by the package signing mechanism against malicous packages being injected into the official Ubuntu mirrors network.

What we want to do instead is configure apt to accept signatures from a third-party repository only on packages being installed from that repository — no cross-signing. Apt's default pinning rules give higher priority to official distro repos, which (in conjunction with proper key management) offers some protection against third-party repos replacing distro-provided packages. (At least, I think that's default. You can use apt-cache policy to inspect the current pin priorities, and if needed you can adjust pinning based on origin to achieve this effect. See man apt_preferences for details.)

The instructions given in Ugo Delle Donne's answer for converting the key to the (legacy) keyring v4 format that apt will accept are correct and helpful, but that's only half of the solution. I'll reiterate them here (cleaned up slightly) so all the steps are consolidated in one place:

  • Download the key:
    • wget https://host.domain.tld/path/to/<keyfile>.<ext>
      (No need for -O or >; wget defaults to saving the file in your current directory with the same filename it has on the server.)
  • Verify that the filetype is "PGP public key block Public-Key (old)":
    • file <keyfile>.<ext>
  • gpg supports a number of key formats, so if your key is in a different format, convert it by importing it into a temp keyring, then exporting it again:
    • gpg --no-default-keyring --keyring ./temp-keyring.gpg --import <keyfile>.<ext>
    • gpg --no-default-keyring --keyring ./temp-keyring.gpg --export --output <your-keyfile-name>.gpg
    • rm temp-keyring.gpg

Now that you have your converted key, do not add it to apt's trusted keystore by copying it into /etc/apt/trusted.gpg.d/. Instead, put it somewhere like /etc/apt/keyrings/. (You might need to create that keyrings directory first.) There's nothing special about that location, it's just a convention recommended by man 5 sources.list in Ubuntu 22.04 and a related Debian Wiki entry.

At this point, nothing has changed and apt doesn't know the key exists. The last step is to modify the specific .list file for the repository to tell apt where to find the key for that specific repo.

  • Edit the file /etc/apt/sources.list.d/<example>.list, and in between deb and the url, add [signed-by=/etc/apt/keyrings/<your-keyfile-name>.gpg]

Now apt will accept that key's signature for all packages in that repo and only that repo.

Notes:

  • If you already have keyring files in /etc/apt/trusted.gpg.d/, you can copy move them to /etc/apt/keyrings/ as-is, and then update all the corresponding .list files so each one has a signed-by field pointing to its own key.
  • If you already have keys in the /etc/apt/trusted.gpg keyring file beyond the official repo keys, this answer details the steps to locate and remove them. You can then follow all the same steps above to set them up the safer way. (Exporting them from that keyring is also possible, but the exact steps are left as an exercise for the reader.)
  • To import a repo's key from a keyserver to a standalone file:
    • gpg --no-default-keyring --keyring <output-file-name>.gpg --keyserver <some.keyserver.uri> --recv-keys <fingerprint>
    • This should give you a key that apt will accept without conversion.
  • Apt is still very trusting, and a malicious or compromised repo can bypass this measure easily because packages currently can run arbitrary shell code as root in their setup scripts. Closing off one attack vector doesn't hurt, though, and progress is (slowly) being made on other fronts.
  • Optionally, you can switch to the newer, more verbose Deb822 format using individual .sources files instead of .list files. It's more work, but personally I find the result far more readable.

Sources:

16
  • 2
    @Hrobky yes, if the key is an old binary-format "public key block" that has been ascii-armored, that will work. However, if the key file is in the newer binary "keybox database" format, which apt doesn't support, it needs to be actually converted to the old public key block format (after dearmoring if applicable). If there's a one-step command for that binary→binary conversion, I haven't encountered it yet.
    – Askeli
    Jan 28, 2021 at 15:42
  • 1
    Great answer. @Askeli could you give an example of a key for which the direct gpg --dearmor works, and one for which it doesn't? Eg am I correct that this mopidy key would work with --dearmor, but this google key wouldn't? Note passing google key directly to gpg --dearmor still exits with error code 0, which suggests... it works?
    – laur
    Jan 28, 2021 at 17:55
  • 1
    @laur I'm afraid I don't have examples. I downloaded, converted, and installed a bunch of keys right around when I wrote this answer, and I'm pretty sure I remember encountering at least one that apt didn't recognize even after --dearmor, which sent me looking for the conversion method in my answer… but I didn't make note of which ones. As a general rule, I'd say there's no harm in piping through --dearmor by default (if the key's not ascii-armored, gpg will exit successfully without changing anything). If apt chokes on the resulting key, then try the binary→binary conversion workaround.
    – Askeli
    Feb 20, 2021 at 20:40
  • 7
    "This means that any third-party repo whose apt signing key is in there is allowed to replace any package on your entire system, no questions asked." -- this is possible even if you use the newer method, no? Because apt will still have no concept of which repository is permitted to ship which packages. Unless you also implement some pinning, but I don't see that in any instructions. Jun 1, 2021 at 20:26
  • 1
    @laur An (ASCII-)armored PGP key is just a base64-encoded version of the non-armored PGP key file, with some header/footer text to indicate it's a PGP key. This is done so that the data can be easily sent using methods which only accept/expect ASCII text, and not arbitrary binary data. Convention is to use the .asc extension for such files, and .gpg for binary key files. Mopidy apparently isn't following that convention. It seems that file will always report "PGP public key block Public-Key (old)" for an armored file, and something more detailed for an unarmored file.
    – Jivan Pal
    Jul 22, 2021 at 0:23
14

I stumbled on the same problem and luckily some other question lighted the way. In my example I was trying to add a teamviewer repository to a recent Kali linux and I was being blocked by the key verification.

I'm quite sure there's a more elegant way to do this but the following steps helped me fix the problem:

  1. Download the relevant key

    wget -O - https://download.teamviewer.com/download/linux/signature/TeamViewer2017.asc > ~/teamviewer.key

  2. Verify the type of file

    file ~/teamviewer.key

    it should be PGP public key block Public-Key (old)

  3. Create a keyring

    gpg --no-default-keyring --keyring ./teamviewer_keyring.gpg --import teamviewer.key

  4. This file is still not a valid key that can be added to /etc/apt/trusted.gpg.d/ since it's a keyring, but from the keyring we can extract the key with

    gpg --no-default-keyring --keyring ./teamviewer_keyring.gpg --export > ./teamviewer.gpg

  5. This file is the key you want to move to the trusted key folder

    sudo mv ./teamviewer.gpg /etc/apt/trusted.gpg.d/

happy sudo apt update!!!

1
  • Do not use this accepted answer and do not put files in /etc/apt/trusted.gpg.d/. See the aswer with the most upvotes for a better solution. Jul 5 at 6:52
8

The reason for this deprecation is because using apt-key add simply appends the gpg key to the trusted global APT keyring. It's similar to the preferred method of adding local_repo.list to /etc/apt/sources.list.d/ instead of using add-apt-repository dep /link/to/repo version, which appends the message to the global sources.list file.

I think it's a bit more awkward to understand than using the .d folder, but essentially we want to get the gpg key into a standalone keyring file, then point to this keyring file in the source listing. The default keyring file location is /usr/share/keyrings, and it can be a .asc or .gpg file. I'm not sure the difference but I do know the global keyring files are binary files, not plaintext.

For example:

Using generic names can be a bit hard to understand sometimes, so here is an example of installing mongoDB:

Get the MongoDB gpg key and add it to a new keyring file

curl https://www.mongodb.org/static/pgp/server-4.2.asc | sudo tee -a /usr/share/keyrings/buster-mongodb-org-4_2.asc

Add a source entry for apt, pointed to this new keyring

echo "deb [signed-by=/usr/share/keyrings/buster-mongodb-org-4_2.asc] https://repo.mongodb.org/apt/debian buster/mongodb-org/4.2 main

Install mongodb from this newly added repo

sudo apt install -y mongodb-org

Reference

This is still new to me, but most of what I know came from this excellent answer in the unix SE

1
  • I'm curious how the file server-4.2.asc from the remote server turned into buster-mongodb-org-4_2.asc on the local side. Is that name important somehow? Jun 3 at 1:46
5

I created a shell script that can download and install keys to be used with [signed-by=] declaration in sources.list.

It's available on github.com/ameinild/add-apt-key.

POSIX Script for installing APT keys

General help

This script will help with installing PGP keys for APT repositories.

This script supports up to 2 arguments:

  • 1st argument is input file. This can be either:
    • An URL - key will be downloaded into current path (using wget or curl)
    • A filename - reads an existing key in current path
    • A path and a filename - reads an existing key in given path
  • 2nd argument is key output path and output name. This can be either:
    • Only filename - output path is set in config, saved as given filename
    • A path and a filename - output path is given here, saved as given filename
    • Only a path (end with /) - output path is given here, filename is taken from existing key
    • Empty - output path is set in config, filename is taken from existing key

This script has a config file /usr/local/etc/add-apt-key.conf, where the following variables can be set:

  • keypath : path to store converted key - default is /usr/share/keyrings
  • verbosity : if set to Yes - displays extra output
  • removetmp : if set to Yes - remove input (non-converted) file

Example 1: (PWD=/root)

sudo add-apt-key https://mariadb.org/mariadb_release_signing_key.asc /usr/local/share/keyrings/

Will download key in /root, convert it and store as /usr/local/share/keyrings/mariadb_release_signing_key.gpg

Example 2: (PWD=/home/user)

sudo add-apt-key /root/mariadb_release_signing_key.asc /usr/local/share/keyrings/mariadbkey

Will use existing key in /root, convert it and store as /usr/local/share/keyrings/mariadbkey.gpg

Example 3: (PWD=/home/user)

sudo add-apt-key mariadb_release_signing_key.asc mariadbkey

Will use existing key in /home/user, convert it and store as /usr/share/keyrings/mariadbkey.gpg

After installing the PGP key, it is also possible to add the key and repository to /etc/apt/sources.list

  • The choice to add this will be presented in the script as the first input option
  • If Yes is chosen, the repository string must be pasted as the second input option

This completes the key installation by adding the corresponding repository line to /etc/apt/sources.list

Installation

Install by running the following commands:

sudo curl -L https://raw.githubusercontent.com/ameinild/add-apt-key/master/add-apt-key -o /usr/local/bin/add-apt-key
sudo curl -L https://raw.githubusercontent.com/ameinild/add-apt-key/master/add-apt-key.conf -o /usr/local/etc/add-apt-key.conf
sudo chmod a+rx /usr/local/bin/add-apt-key
5
  • 5
    Therefore, it is clearly demonstrated above that Linux is definitely not adapted to average end-users. Those Ubuntu and others should warned that you need serious advanced skills and have to be willing to spend a lot of time training, searching, and dealing , with those issues... even-more, with small guarantee that you that whatever you do will work or not create further problems. That's dishonesty. Jul 16, 2021 at 17:19
  • 1
    I'm pretty sure that future versions of Ubuntu will have adapted its own scripts to the "new" way of installing PGP keys. In the meantime, I've written a script to help other users achieve the closest possible to automating this. If you find it too advanced and not useful that's OK, but it was actually meant as a help. Jul 16, 2021 at 17:25
  • The script is updated with an option to write GPG key and repository directly to /etc/apt/sources.list Nov 1, 2021 at 19:00
  • Thanks for this! May 24 at 10:26
  • @YannMonnier you are 100% right. If the Ubuntu developers cannot match their "security concerns" with what the community actually needs, the Ubuntu desktop will just stop being a viable option. I'm a big fan of Slackware, where the tools are much more streamlined and simple (although documentation is lacking). They are also likely "less secure", but we're not running a bank here - it's a PC!
    – levitopher
    Aug 6 at 16:00
1

As a direct workalike, replace apt-key add with gpg --dearmor:

curl [KEYURL] | sudo gpg --dearmor --yes -o /etc/apt/trusted.gpg.d/[KEYFILE].gpg

However, this is not recommended (other than as a workalike to apt-key) since all keys in the trusted directory are unconditionally trusted; it is better to put the output in a (non-globally) trusted directory (as others have suggested), and have each source specify which key(s) to trust, individually.

7
  • 1
    Don't know who downvoted you, probably due to 'quality' of answer compared to the others, I do have a suggestion though, this will do the same, but is a tad 'simpler': curl [KEYURL] | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/[KEYFILE].gpg
    – Lockszmith
    Jun 4 at 21:27
  • Thanks, that is indeed much better. Updated.
    – nyet
    Jun 5 at 22:32
  • Note that I can't find a way to have -o force overwrite an existing file, which makes this less suitable for automation.
    – nyet
    Jun 5 at 22:45
  • 1
    just add --yes
    – Lockszmith
    Jun 6 at 15:49
  • Thank you, updated.
    – nyet
    Jun 7 at 16:18
0

Keys for use by apt are stored in /etc/apt/trusted.gpg.d/. apt-key managed these keyrings for you, but now that it's deprecated you need to choose a suitable file name <KEYRING> for the keyring yourself.

If you have the key already as a local file <FILE>, run

gpg --no-default-keyring --keyring=gnupg-ring:/etc/apt/trusted.gpg.d/<KEYRING>.gpg --import <FILE>

To directly read the key from <URL>, run

curl -sSfL <URL> | gpg --no-default-keyring --keyring=gnupg-ring:/etc/apt/trusted.gpg.d/<KEYRING>.gpg --import

Note: the prefix gnupg-ring: before the keyring name is required to create the keyring in the apt compatible (legacy) v4 format, rather than the (newer) keybox v1 format.

8
  • how should I modify the command you've mentioned, if I wanted to add gpg key: EBB4CCF6A72BC110 | 55D9B3F8D3E163D4CED77D9CEBB4CCF6A72BC110 from this PPA: https://launchpad.net/~ufleisch/+archive/ubuntu/kid3. I tried: curl -sSfL https://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=index&search=0x55D9B3F8D3E163D4CED77D9CEBB4CCF6A72BC110 | gpg --no-default-keyring --keyring=gnupg-ring:/etc/apt/trusted.gpg.d/<KEYRING>.gpg --import but it didn't work.
    – Jags
    Apr 25, 2021 at 0:32
  • (1) What should be the <URL> in case of this PPA: https://launchpad.net/~ufleisch/+archive/ubuntu/kid3 ? (2) Should I replace <KEYRING>.gpg with gnupg-ring.gpg ? Thanks alot.
    – Jags
    Apr 25, 2021 at 0:32
  • 2
    @Jags curl -sSfL 'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x55d9b3f8d3e163d4ced77d9cebb4ccf6a72bc110' | sudo gpg --no-default-keyring --keyring=gnupg-ring:/etc/apt/trusted.gpg.d/kid.gpg --import
    – kynan
    Apr 25, 2021 at 21:23
  • Thank you so much, and one more question please. When I wanna import multiple keys at once for a new installation, can I just add more URLs like curl -sSfL <URL> <URL> <URL> or no? Thank you.
    – Jags
    Apr 25, 2021 at 22:58
  • The key was added just fine but now when I run sudo apt update, I'm getting alot of eerors like this: W: http://ppa.launchpad.net/ufleisch/kid3/ubuntu/dists/hirsute/InRelease: The key(s) in the keyring /etc/apt/trusted.gpg.d/kid.gpg are ignored as the file is not readable by user '_apt' executing apt-key. Thanks alot.
    – Jags
    Apr 26, 2021 at 0:37
0

All of the answers here are great, What I'm sharing here is what I took from all of these answers, and automated to make setting up machines easier for me.
Although adding an apt source is a rare occasion per machine, it still is something I do on multiple machines, cloud machines, etc...

The following is a bash script I wrote for myself to add the stack of APT sources on an ubuntu/pop-os based machine I use for DevOps work:

NOTE: Don't just copy paste, if you don't understand what's going on - ask. These are the type of actions no person should take lightly.

My add-my-apt-repos.sh script (GH🔗):

#! /usr/bin/env bash

# Make sure the /usr/share/keyrings dir exists
sudo mkdir -p /usr/share/keyrings 2>&1 > /dev/null

# Make sure all of the basic required tools are installed for the code
# below to work
sudo apt-get install --yes --no-install-recommends \
    curl gnupg software-properties-common apt-transport-https

# some utility variables, _YES is optionally '--yes'
[[ ! -z "$1" && "$1" == '--yes' ]] && _YES='--yes'
_OS=$(lsb_release -is | awk '{ print tolower($0) }')
[[ $_OS == 'pop' ]] && _OS='ubuntu'
_REL=$(lsb_release -rs) # Release
_CNM=$(lsb_release -cs) # CodeName
_ARC=$(dpkg --print-architecture) # Architecture

# The function that does the _Heavy Lifting_.
# see the code that follows for the parameter signature
function add_repo() {
    REPO_FQDN=$1 #'download.docker.com'
    GPG_KEY_URL=${2:-https:\/\/$REPO_FQDN\/gpg}
    GPG_KEY_PATH=/usr/share/keyrings/$REPO_FQDN.gpg
    REPO_ARCH=${3:-${_ARC}}
    [[ $REPO_ARCH == '-' ]] && REPO_ARCH='' || REPO_ARCH="arch=$REPO_ARCH"
    REPO_URL=${4:-https:\/\/$REPO_FQDN}
    REPO_SUITE=${5:-$_CNM}
    REPO_CMP=${6:-main}
    
    curl -fsSL $GPG_KEY_URL | sudo gpg --dearmor -o $GPG_KEY_PATH $_YES
    echo "Key created: $GPG_KEY_PATH"
    echo "deb [$(echo "$REPO_ARCH signed-by=$GPG_KEY_PATH" | xargs )] $REPO_URL $REPO_SUITE $REPO_CMP" | \
                sudo tee /etc/apt/sources.list.d/$REPO_FQDN.list > /dev/null
    echo "APT source list added: /etc/apt/sources.list.d/$REPO_FQDN.list"
}

#Long line - 197 characters long
#add_repo  REPO_FQDN/Name                GPG_KEY_URL                                             REPO_ARCH  REPO_URL                                         REPO_SUITE  REPO_CMP # TBD: PIN_PRIORITY
#defaults: <required>                   'https://$REPO_FQDN/gpg'                                 $_ARC     'https://$REPO_FQDN'                              $_CNM      'main'    #      <optional>
#         ----------------------------  ------------------------------------------------------- ---------- ------------------------------------------------ ----------- ---------
# for: docker-ce docker-ce-cli containerd.io docker-compose-plugin
# Also don't forget:
#   remove: docker docker-engine docker.io containerd runc 
#   possibly remove docker-compose and install: https://github.com/docker/compose-switch
add_repo  'download.docker.com'         "https://download.docker.com/linux/$_OS/gpg"            ''         "https://download.docker.com/linux/$_OS"         ''          'stable'
# for: anydesk
add_repo  'deb.anydesk.com'             'https://keys.anydesk.com/repos/DEB-GPG-KEY'            '-'        'http://deb.anydesk.com/'                        'all'       ''
# for: google-cloud-cli
add_repo  'packages.cloud.google.com'   'https://packages.cloud.google.com/apt/doc/apt-key.gpg' '-'        'https://packages.cloud.google.com/apt'          'cloud-sdk' ''
# for: code (optionally: powershell dotnet-*)
add_repo  'packages.microsoft.com'      'https://packages.microsoft.com/keys/microsoft.asc'     ''         "https://packages.microsoft.com/$_OS/$_REL/prod" ''          ''
# for: microsoft-edge-stable
add_repo  'packages.microsoft.com-edge' 'https://packages.microsoft.com/keys/microsoft.asc'     ''         'http://packages.microsoft.com/repos/edge'       'stable'    ''
# for: terraform
add_repo  'apt.releases.hashicorp.com'  'https://apt.releases.hashicorp.com/gpg'                ''         'https://apt.releases.hashicorp.com'             ''          ''

# I really LOVE xscreensavers, but it's been stuck in limbo on the
# `stable` repos, so I install it from the `unstable`, aka `sid`, suite.
# To do that safely, I make sure the repo is pinned to a lower priority.
# I do this BEFORE I add the repo.

# # Debian sid (unstable) as low-priority option
(echo 'Package: *'; echo 'Pin: release a=unstable'; echo 'Pin-Priority: 200') | sudo tee /etc/apt/preferences.d/unstable > /dev/null
# # pin xscreensaver to unstable
(echo 'Package: xscreenaver*'; echo 'Pin: release a=unstable'; echo 'Pin-Priority: 2000') | sudo tee /etc/apt/preferences.d/xscreensaver > /dev/null

# for: xscreensaver xscreensaver-data xscreensaver-data-extra
#      xscreensaver-screensaver-bsod xscreensaver-screensaver-webcollage
# Add the unstable/sid repo - THIS IS DANGEROUS without the pinning via
# /etc/apt/preferences.d files created by the code above.
sudo apt-add-repository $_YES --no-update "deb [arch=amd64] http://http.us.debian.org/debian sid main non-free contrib"

# Finally, run `apt update` to check that everything completed successfully
sudo apt update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.