Перейти к содержимому

Apt key что это

  • автор:

Пакетный менеджер APT

Advanced Packaging Tool – набор утилит для управления программными пакетами в операционных системах основанных на Debian. APT предоставляет дружественную надстройку над DPKG и позволяет:

APT является одной из базовых программ и включена в состав Ubuntu.

Настройки

Все файлы настроек APT хранятся в директории /etc/apt.

apt.conf

/etc/apt/apt.conf – основной файл настроек, используемый всеми инструментами из состава APT. Описание всех возможных настроек и опций можно прочитать в документации к нему:

apt.conf.d

Директория содержащая в себе файлы конфигурации, аналогичные по синтаксису apt.conf. При помощи этой директории можно быстро и удобно манипулировать настройками APT добавляя или удаляя подготовленные файлы с настройками.

auth.conf

Файл, содержащий ключи, для авторизации в репозиториях. Например, туда добавляются логины и пароли от репозиториев к купленным в Центре приложений программам.

sources.list
sources.list.d

Директория с файлами репозиторий, по назначению аналогичных sources.list. Каждый репозиторий описывается в отдельном файле.

Использование

В APT входит несколько утилит, выполняющих отдельные задачи.

apt-get

apt-get это утилита управления пакетами. apt-get требует прав суперпользователя для своей работы.

Починка базы пакетов

apt-get также используется для устранения сбоев в базе пакетов вызванных нарушенными зависимостями. Разрешение зависимостей производится командой:

apt-cache

apt-cache – утилита, позволяющая выполнять запросы к кешу APT.

apt-key

apt-key служит для добавления ключей от репозиториев в систему. Ключи защищают репозитории от возможности подделки пакета. Подробнее смотрите в статье Репозитории.

Записки IT специалиста

Аpt-key is deprecated или управление ключами в современных выпусках Debian и Ubuntu

  • Автор: Уваров А.С.
  • 06.09.2022

apt-key-deprecated-000.pngМногие базовые действия в дистрибутивах Linux не меняются множество лет и для многих стали уже привычкой. А привычки — вещь такая: привыкнуть легко, сложно переучиться. Поэтому изменения базовых вещей многими воспринимается в штыки и вызывает крайне негативные эмоции. Apt-key — утилита командной строки для управления ключами пакетного менеджера APT и когда ее объявили устаревшей, то многим это не понравилось. Однако на то были свои причины, а новая система управления ключами во многом даже проще и удобнее, нужно лишь разобраться и привыкнуть.

Научиться настраивать MikroTik с нуля или систематизировать уже имеющиеся знания можно на углубленном курсе по администрированию MikroTik. Автор курса, сертифицированный тренер MikroTik Дмитрий Скоромнов, лично проверяет лабораторные работы и контролирует прогресс каждого своего студента. В три раза больше информации, чем в вендорской программе MTCNA, более 20 часов практики и доступ навсегда.

Коротко о том, что такое ключ репозитория и для чего он нужен. Любой репозиторий содержит пакеты, которые передаются по открытым каналам и перед тем, как устанавливать их в систему нам следует убедиться в их подлинности. Для этого все пакеты в репозитории подписаны закрытым ключом репозитория, а чтобы проверить их подлинность нам потребуется открытый ключ или просто ключ.

Для того, чтобы система могла использовать ключ его нужно установить в системное хранилище, которое располагается в /etc/apt/trusted.gpg, для чего использовалась команда:

Однако если вы выполните команду в последних версиях Debian, Ubuntu и других основанных на них дистрибутивах, то получите предупреждение:

Ключ при этом добавится и, в принципе, вы можете продолжать пользоваться старым способом не обращая внимание на предупреждения.

Но разработчики не просто так объявили apt-key устаревшим, на это есть серьезные причины. Дело в том, что APT безоговорочно доверяет любому ключу в trusted.gpg для любого репозитория, что дает возможность загрузить из стороннего репозитория пакеты, подписанные ключом другого репозитория и заменить таким образом любой пакет в системе.

Чтобы устранить потенциальную брешь в безопасности была введена новая система, когда каждый репозиторий доверяет только собственному ключу, а сами ключи помещаются в специальное хранилище, к которому имеет доступ только суперпользователь. В настоящее время это директория /usr/share/keyrings, согласно документации там следует размещать ключи, дальнейшее управление которыми предполагается с помощью APT или DPKG. Для ключей управляемых локально предназначена директория /etc/apt/keyrings. В системах до Debian 12 и Ubuntu 22.04 ее следует создать самостоятельно с разрешением 755.

Ключ должен быть в двоичной форме (без ASCII-Armor) и иметь имя:

Где repo — короткая часть имени репозитория.

Допускается также иметь рядом текстовую версию ключа (с ASCII-Armor) с именем:

Также в строке подключения репозитория можно явно указать связанный с ним ключ:

На практике очень часто требование снять ASCII-Armor не соблюдается и в /usr/share/keyrings кладется текстовая версия ключа. Однако в документации Debian крайне не советуется так делать.

Далее мы рассмотрим на практике приемы работы с ключами в современных операционных системах.

Определение типа ключа

Выше мы говорили, что ключ может быть двух типов: бинарный и текстовый, т.е. с ASCII-Armor или без. Пусть вас не смущает новый непонятный термин, ASCII-Armor — это привычный всем текстовый формат ключей в кодировке Base64.

apt-key-deprecated-001.png

Знакомо, не правда ли? Это и есть ключ с ASCII-Armor. Такие ключи наиболее распространены, так как текстовый формат более удобен при передаче в сетях связи. Убедиться, что перед вами ключ в ASCII формате можно просто прочитав файл, например, командой cat:

Или при помощи команды:

В случае текстового формата вы увидите:

Если это бинарный ключ:

Почему мы уделяем этому столько внимания? Потому что если делать все по правилам, то ключи должны быть в бинарном формате, а для этого нужно понимать в каком виде мы получили исходный ключ. В большинстве случаев это будет текстовый ключ с ASCII-Armor.

Удаление старых ключей

Перед тем, как устанавливать ключ в новое хранилище нам нужно удалить его из старого хранилища /etc/apt/trusted.gpg. Для этого сначала получим список ключей командой:

В выводе будет полный список установленных в систему ключей.

apt-key-deprecated-002.png

Находим и копируем идентификатор нужного ключа, затем удаляем его командой:

Идентификатор можно взять как есть, с пробелами, только заключить его в двойные кавычки. Либо использовать два последних блока, так для указанного выше ключа можно ввести:

Кстати, именно эти две команды являются на сегодняшний день допустимыми для использования с apt-key.

Получение и установка текстовых ключей OpenPGP (c ASCII-Armor)

Адрес ключа репозитория обычно можно узнать в документации продукта, затем нам потребуется его скачать и установить в новое хранилище. Для скачивания можно использовать wget:

Или curl:

Затем его следует преобразовать в бинарный формат и поместить в хранилище, эту команду следует выполнять с правами суперпользователя:

Можно ли упростить этот процесс, можно, для этого используем конвейер:

Возможно, многие обратили внимание на чередование ключей в командах. Так wget по умолчанию скачивает файл, а curl выдает содержимое запроса в стандартный вывод. Поэтому чтобы сохранить файл с исходным именем мы использовали ключ -O для curl, и наоборот, чтобы получить содержимое файла в stdout мы запустили wget с ключом -O-, который предполагает вывод в файл, но если вместо файла указан дефис, то идет вывод в стандартный поток. Это небольшая мелочь, которую надо всегда помнить при работе с этими утилитами.

Обе команды должны быть запущены под root, если же вы предпочитаете sudo, то следует сделать так:

В чем разница? Основная часть работы выполняется с правами обычного пользователя, затем поток вывода передается утилите tee, которая записывает его в файл и выводит на экран, чтобы избежать последнего мы перенаправил ее вывод в /dev/null. При этом только tee запускается с правами суперпользователя.

Получение и установка бинарных ключей OpenPGP (без ASCII-Armor)

Мы бы хотели привести пример, но не можем припомнить чтобы в каком-то репозитории применялись бинарные ключи. Но случаи бывают разные. Для этого вам понадобятся права суперпользователя или sudo:

Здесь все просто, мы сразу помещаем скачиваемый файл в хранилище под нужным именем.

Получение ключей OpenPGP с сервера ключей

Использование серверов ключей достаточно редкий сценарий, но он тоже иногда используется, и вы должны уметь это делать. Для того, чтобы получить ключ надо знать его ID, точнее два его последних блока:

Также вы можете использовать ID ключа целиком, если он содержит пробелы, то оберните его в двойные кавычки.

После выполнения данной операции в домашней директории пользователя будет создано локальное хранилище в скрытой директории .gnupg/trustdb.gpg.

Теперь нам нужно экспортировать оттуда ключ в хранилище, команда должна выполняться под тем же самым пользователем, который получил ключ в предыдущей команде, если это root:

А если нужно получить текстовый ключ:

Если ключ получал непривилегированный пользователь, то работаем через tee и sudo:

Можно ли сразу получить и экспортировать ключ? Можно. Если вы внимательно разобрали команды выше, то следующая не покажется вам китайским заклинанием:

Данную команду следует выполнять от имени суперпользователя, ключ —no-default-keyring предписывает не использовать локальное хранилище в домашней директории пользователя, оттуда не будет ничего считываться и не будет ничего записано.

Удаление ключей из хранилища

Для удаления ключа достаточно удалить соответствующий ему файл, для этого вам потребуются права root:

Как видим, управлять ключами в современных системах несложно. Надеемся, что данная статья будет вам полезна и поможет быстрее перейти к использованию новых и безопасных инструментов.

Научиться настраивать MikroTik с нуля или систематизировать уже имеющиеся знания можно на углубленном курсе по администрированию MikroTik. Автор курса, сертифицированный тренер MikroTik Дмитрий Скоромнов, лично проверяет лабораторные работы и контролирует прогресс каждого своего студента. В три раза больше информации, чем в вендорской программе MTCNA, более 20 часов практики и доступ навсегда.

Помогла статья? Поддержи автора и новые статьи будут выходить чаще:

Поддержи проект!

Или подпишись на наш Телеграм-канал: Подпишись на наш Telegram-канал

What is apt-key ?

Each distribution has a release file which contains indices of binary and source packages that can be installed from this distribution . apt-key is used to add , delete , list , and export public keys used by apt to verify the signature of a release file .

If a public key for a distribution does not exist , then apt will fail to verify the signature of its release file , and it will issue an error . The downloaded release file is then disregarded , and apt will use the previous indices of binary and source packages gotten from this distribution , if they exist.

apt-key : How verification works , Listing the distributions installed public keys , Adding the public key of a distribution , Deleting the public key of a distribution .

How verification works ?

A distribution source , the location from which we are going to download its release file , can either be located in the file /etc/apt/sources.list or in the directory /etc/apt/sources.list.d/ .

The public keys used to verify a distribution release file can be located either in the /etc/apt/trusted.gpg.d/ directory on in the /etc/apt/trusted.gpg file .

When debian is installed , the package debian-archive-keyring is also installed . This package contains public keys which can be used to verify the release files of distributions authored by the debian project .

If the apt-get update command is issued, using the previous /etc/apt/sources.list file , and the public keys in the /etc/apt/trusted.gpg.d directory , then the result will be :

apt by default , will only accept the release files which are signed , and which have their public key installed . The release files of the distributions authored by the debian project are signed , and have their public keys installed , as such they were successfully downloaded. The release files from winehq and from Microsoft don’t have their public keys installed , as such they are disregarded and they have caused apt to issue an error.

Each distribution has a Release , InRelease and Release.gpg files which are located in :

The Release file has its signature located inside the Release.gpg file whereas the the InRelease file has its signature inside.

A release file is signed by the distribution author private key. The signature will contain the hash of the release file . The hash is a mathematical code calculated by a function from a message , and is used to uniquely identify the message . The chances of hash collision , which is two messages having the same code , depends on the hashing algorithm. .

The signature of the release file also contains , the timestamp of when it was signed and the public key id of the author who signed this message . The public key id is the low order 64 bits of its fingerprint , and it consists of 16 hexadecimal digits ; It is used to locate the public key which will be used to verify the message .

apt will use the public key gotten from the author of the distribution and identified by the key id to read the hashed value in the signature . The hashed value in the signature , is the hash of the original release file . apt will also calculate the hash of : the downloaded Release file , or of the message in the downloaded InRelease file , and compare it to the hash value read from the signature . If they are equal then the downloaded release file has been successfully verified , else the verification has failed and the release file is disregarded .

Listing the distributions installed public keys

The enlighter /etc/apt/trusted.gpg file and files in the enlighter /etc/apt/trusted.gpg.d/ directory are known as keyring since they can contain one or more public key which can be used to verify the signatures of release files .

The list option of the apt-key command can be used to list the public keys that are installed in the enlighter /etc/apt/trusted.gpg.d/ directory or in the enlighter /etc/apt/trusted.gpg file.

Adding the public key of a distribution

The public key for a distribution can either be in ASCII armored format , or it can be in binary packet format . The binary packet format usually has the .gpg extension . The ASCII armored format usually has the .asc extension .

The ASCII armored format starts with ——BEGIN PGP PUBLIC KEY BLOCK—— followed by one or more optional headers such as Version , followed by an empty line , followed by the public key binary packet format encoded into ASCII radix 64 , and it ends with ——END PGP PUBLIC KEY BLOCK—— .

In ASCII radix 64 , each 6 bits represents one of the characters : [a-zA-Z0-9+/] , so for example the six bits value 0 represents A , and the six bits value 34 represents i . To convert to ASCII radix 64 , each six bits of the input are taken at a time , and converted to ASCII based on their value ; for example if their six bits value is 0 they are converted to A .

enlighter apt-get add public_key_file can be used to add a public key in either formats . If the file is stored remotely wget , for example , can first be used to download it .

As an example to add the public key for the stable distribution authored by Microsoft and which contains the visual studio code application , it can be done like this :

Instead of separately downloading and adding the file , we can use apt-key adv —fetch-keys key_url to download and add the public key .

As an example , to add the source for the buster distribution authored by WineHQ , and which contains the wine application , it can be done like this :

Instead of using apt-key to add the public key , it can be placed directly inside the /etc/apt/trusted.gpg.d/ directory. If it is in ASCII armored format , it must have an .asc extension , and if it is in the binary packet format , it must have a .gpg extension.

As an example , to add the source for the stable distribution authored by Opera , and which contains the opera web browser , it can be done like this :

Deleting the public key of a distribution

enlighter apt-key del <public_key_fingerprint> can be used to delete an installed public key .

apt-key — Man Page

apt-key is used to manage the list of keys used by apt to authenticate packages. Packages which have been authenticated using these keys will be considered trusted.

Use of apt-key is deprecated, except for the use of apt-key del in maintainer scripts to remove existing keys from the main keyring. If such usage of apt-key is desired the additional installation of the GNU Privacy Guard suite (packaged in gnupg) is required.

apt-key(8) will last be available in Debian 11 and Ubuntu 22.04.

Supported Keyring Files

apt-key supports only the binary OpenPGP format (also known as «GPG key public ring») in files with the «gpg» extension, not the keybox database format introduced in newer gpg(1) versions as default for keyring files. Binary keyring files intended to be used with any apt version should therefore always be created with gpg —export.

Alternatively, if all systems which should be using the created keyring have at least apt version >= 1.4 installed, you can use the ASCII armored format with the «asc» extension instead which can be created with gpg —armor —export.

Commands

Add a new key to the list of trusted keys. The key is read from the filename given with the parameter filename or if the filename is — from standard input.

It is critical that keys added manually via apt-key are verified to belong to the owner of the repositories they claim to be for otherwise the apt-secure(8) infrastructure is completely undermined.

Note: Instead of using this command a keyring should be placed directly in the /etc/apt/trusted.gpg.d/ directory with a descriptive name and either «gpg» or «asc» as file extension.

Remove a key from the list of trusted keys.

Output the key keyid to standard output.

Output all trusted keys to standard output.

List trusted keys with fingerprints.

Pass advanced options to gpg. With adv —recv-key you can e.g. download key from keyservers directly into the trusted set of keys. Note that there are no checks performed, so it is easy to completely undermine the apt-secure(8) infrastructure if used without care.

Update the local keyring with the archive keyring and remove from the local keyring the archive keys which are no longer valid. The archive keyring is shipped in the archive-keyring package of your distribution, e.g. the debian-archive-keyring package in Debian.

Note that a distribution does not need to and in fact should not use this command any longer and instead ship keyring files in the /etc/apt/trusted.gpg.d/ directory directly as this avoids a dependency on gnupg and it is easier to manage keys by simply adding and removing files for maintainers and users alike.

Perform an update working similarly to the update command above, but get the archive keyring from a URI instead and validate it against a master key. This requires an installed wget(1) and an APT build configured to have a server to fetch from and a master keyring to validate. APT in Debian does not support this command, relying on update instead, but Ubuntu’s APT does.

Options

Note that options need to be defined before the commands described in the previous section.

With this option it is possible to specify a particular keyring file the command should operate on. The default is that a command is executed on the trusted.gpg file as well as on all parts in the trusted.gpg.d directory, though trusted.gpg is the primary keyring which means that e.g. new keys are added to this one.

Deprecation

Except for using apt-key del in maintainer scripts, the use of apt-key is deprecated. This section shows how to replace existing use of apt-key.

If your existing use of apt-key add looks like this:

wget -qO- https://myrepo.example/myrepo.asc | sudo apt-key add —

Then you can directly replace this with (though note the recommendation below):

wget -qO- https://myrepo.example/myrepo.asc | sudo tee /etc/apt/trusted.gpg.d/myrepo.asc

Make sure to use the «asc» extension for ASCII armored keys and the «gpg» extension for the binary OpenPGP format (also known as «GPG key public ring»). The binary OpenPGP format works for all apt versions, while the ASCII armored format works for apt version >= 1.4.

Recommended: Instead of placing keys into the /etc/apt/trusted.gpg.d directory, you can place them anywhere on your filesystem by using the Signed-By option in your sources.list and pointing to the filename of the key. See sources.list(5) for details. Since APT 2.4, /etc/apt/keyrings is provided as the recommended location for keys not managed by packages. When using a deb822-style sources.list, and with apt version >= 2.4, the Signed-By option can also be used to include the full ASCII armored keyring directly in the sources.list without an additional file.

Files

Keyring of local trusted keys, new keys will be added here. Configuration Item: Dir::Etc::Trusted.

File fragments for the trusted keys, additional keyrings can be stored here (by other packages or the administrator). Configuration Item Dir::Etc::TrustedParts.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *