9. Debian Package Management

After the basics of Linux, it is time to learn the package management system of a Debian-based distribution. In such distributions, including Kali, the Debian package is the canonical way to make software available to end-users. Understanding the package management system will give you a great deal of insight into how Kali is structured, enable you to more effectively troubleshoot issues, and help you quickly locate help and documentation for the wide array of tools and utilities included in Kali Linux.

In this chapter, we will introduce the Debian package management system and introduceĀ dpkgĀ and the APT suite of tools. One of the primary strengths of Kali Linux lies in the flexibility of its package management system, which leverages these tools to provide near-seamless installation, upgrades, removal, and manipulation of application software, and even of the base operating system itself. It is critical that you understand how this system works to get the most out of Kali and streamline your efforts. The days of painful compilations, disastrous upgrades, debuggingĀ gcc,Ā make, andĀ configureĀ problems are long gone, however, the number of available applications has exploded and you need to understand the tools designed to take advantage of them. This is also a critical skill because there are a number of security tools that, due to licensing or other issues, cannot be included in Kali but have Debian packages available for download. It is important that you know how to process and install these packages and how they impact the system, especially when things do not go as expected.

We will begin with some basic overviews of APT, describe the structure and contents of binary and source packages, take a look at some basic tools and scenarios, and then dig deeper to help you wring every ounce of utility from this spectacular package system and suite of tools.

9.1. Introduction to APT

Letā€™s begin with some basic definitions, an overview, and some history about Debian packages, starting withĀ dpkgĀ and APT.

9.1.1. Relationship between APT and dpkg

A Debian package is a compressed archive of a software application. AĀ binary packageĀ (aĀ .debĀ file) contains files that can be directly used (such as programs or documentation), while aĀ source packageĀ contains the source code for the software and the instructions required for building a binary package. A Debian package contains the applicationā€™s files as well as otherĀ metadataĀ including the names of the dependencies the application needs, as well as scripts that enable the execution of commands at different stages in the packageā€™s lifecycle (installation, upgrades, and removal).

TheĀ dpkgĀ tool was designed to process and installĀ .debĀ packages, but if it encountered an unsatisfied dependency (like a missing library) that would prevent the package from installing,Ā dpkgĀ would simply list the missing dependency, because it had no awareness or built-in logic to find or process the packages that might satisfy those dependencies. The Advanced Package Tool (APT), includingĀ aptĀ andĀ apt-get, were designed to address these shortcomings and could automatically resolve these issues. We will talk about bothĀ dpkgĀ and the APT tools in this chapter.

The base command for handling Debian packages on the system isĀ dpkg, which performs installation or analysis ofĀ .debĀ packages and their contents. However,Ā dpkgĀ has only a partial view of the Debian universe: it knows what is installed on the system and whatever you provide on the command line, but knows nothing of the other available packages. As such, it will fail if a dependency is not met. APT addresses the limitations.

APT is a set of tools that help manage Debian packages, or applications on your Debian system. You can use APT to install and remove applications, update packages, and even upgrade your entire system. The magic of APT lies in the fact that it is a complete package management system that will not only install or remove a package, but will consider the requirements and dependencies of the packaged application (and even their requirements and dependencies) and attempt to satisfy them automatically. APT relies onĀ dpkgĀ but APT differs fromĀ dpkg, as the former installs the latest package from an online source and works to resolve dependencies whileĀ dpkgĀ installs a package located on your local system and does not automatically resolve dependencies.

If you have been around long enough to remember compiling programs withĀ gccĀ (even with the help of utilities such asĀ makeĀ andĀ configure), you likely remember that it was a painful process, especially if the application had several dependencies. By deciphering the various warnings and error messages, you may have been able to determine which part of the code was failing and most often that failure was due to a missing library or other dependency. You would then track down that missing library or dependency, correct it, and try again. Then, if you were lucky, the compile would complete, but often the build would fail again, complaining about another broken dependency.

APT was designed to help alleviate that problem, collate program requirements and dependencies, and resolve them. This functionality works out-of-the-box on Kali Linux, but it isnā€™t foolproof. It is important that you understand how Debian and Kaliā€™s packaging system works because you will need to install packages, update software, or troubleshoot problems with packages. You will use APT in your day-to-day work with Kali Linux and in this chapter, we will introduce you to APT and show you how to install, remove, upgrade, and manage packages, and even show you how to move packages between different Linux distributions. We will also talk about graphical tools that leverage APT, show you how to validate the authenticity of packages, and delve into the concept of a rolling distribution, a technique that brings daily updates to your Kali system.

Before we dig in and show you how to useĀ dpkgĀ and APT to install and manage packages, it is important that we delve into some of the inner workings of APT and discuss some terminology surrounding it.

Package Source and Source Package

The wordĀ sourceĀ can be ambiguous. A source packageā€”a package containing the source code of a programā€”should not be confused with a package sourceā€”a repository (website, FTP server, CD/DVD-ROM, local directory, etc.) that contains packages.

APT retrieves its packages from a repository, a package storage system or simply, ā€œpackage sourceā€. TheĀ /etc/apt/sources.listĀ file lists the different repositories (or sources) that publish Debian packages.

9.1.2. Understanding the sources.list File

TheĀ sources.listĀ file is the key configuration file for defining package sources, and it is important to understand how it is laid out and how to configure it since APT will not function without a properly defined list of package sources. Letā€™s discuss its syntax, take a look at the various repositories that are used by Kali Linux, and discuss mirrors and mirror redirection, then you will be ready to put APT to use.

Each active line of theĀ /etc/apt/sources.listĀ file (and of theĀ /etc/apt/sources.list.d/*.listĀ files) contains the description of a source, made of three parts separated by spaces. Commented lines begin with aĀ #Ā character:

#deb cdrom:[Debian GNU/Linux 2020.3 _Kali-rolling_ - Official Snapshot amd64 LIVE/INSTALL Binary 20200728-20:25]/ kali-last-snapshot contrib main non-free

deb http://http.kali.org/kali kali-rolling main non-free contrib

Letā€™s take a look at the syntax of this file. The first field indicates the source type:

  • debĀ for binary packages.
  • deb-srcĀ for source packages.

The second field gives the base URL of the source: this can consist of a Kali mirror or any other package archive set up by a third party. The URL can start withĀ file://Ā to indicate a local source installed in the systemā€™s file hierarchy, withĀ http://Ā to indicate a source accessible from a web server, or withĀ ftp://Ā for a source available on an FTP server. The URL can also start withĀ cdrom:Ā for CD/DVD-ROM/Blu-ray disc-based installations, although this is less frequent since network-based installation methods are more and more common.

TheĀ cdromĀ entries describe the CD/DVD-ROM you have. Contrary to other entries, a CD/DVD-ROM is not always available, since it has to be inserted into the drive and usually only one disc can be read at a time. For those reasons, these sources are managed in a slightly different way and need to be added with theĀ apt-cdromĀ program, usually executed with theĀ addĀ parameter. The latter will then request the disc to be inserted in the drive and will browse its contents looking forĀ PackagesĀ files. It will use these files to update its database of available packages (this operation is usually done by theĀ apt updateĀ command). After that, APT will request the disc if it needs a package stored on it.

The syntax of the last field depends on the structure of the repository. In the simplest cases, you can easily indicate a subdirectory (with a required trailing slash) of the desired source (this is often a simple ā€œ./ā€, which refers to the absence of a subdirectoryā€”the packages are then directly at the specified URL). But in the most common case, the repositories will be structured like a Kali mirror, with multiple distributions each having multiple components. In those cases, name the chosen distribution, then the components (or sections) to enable. Letā€™s take a moment to introduce these sections.

Debian and Kali use three sections to differentiate packages according to the licenses chosen by the authors of each work. A difference between Debian and Kali is that, Debian only has main enabled by default, whereas Kali has all three enabled by default.

mainĀ contains all packages that fully comply with theĀ Debian Free Software Guidelines.

TheĀ non-freeĀ archive is different because it contains software that does not (entirely) conform to these principles but which can nevertheless be distributed without restrictions.

contribĀ (contributions) is a set of open source software that cannot function without some non-free elements. These elements may include software from theĀ non-freeĀ section or non-free files such as game ROMs, BIOS of consoles, etc.Ā contribĀ also includes free software whose compilation requires proprietary elements, such as VirtualBox, which requires a non-free compiler to build some of its files.

Now, letā€™s take a look at the standard Kali Linux package sources, or repositories.

9.1.3. Kali Repositories

A standardĀ sources.listĀ file for a system running Kali Linux refers to one repository (kali-rolling) and the three previously mentioned components:Ā main,Ā contrib, andĀ non-free:

# Main Kali repository
deb http://http.kali.org/kali kali-rolling main contrib non-free

Letā€™s take a look at the Kali repositories.

The Kali-Rolling Repository

This is the main repository for end-users. It should always contain installable and recent packages. It is managed by a tool that merges Debian Testing and the Kali-specific packages in a way that ensures that each packageā€™s dependencies can be satisfied within kali-rolling. In other words, barring any bug in maintainer scripts, all packages should be installable.

Since Debian Testing evolves daily, so does Kali Rolling. The Kali-specific packages are also regularly updated as we monitor the upstream releases of the most important packages.

The Kali-Dev Repository

This repository is not for public use. It is a space where Kali developers resolve dependency problems arising from the merge of the Kali-specific packages into Debian Testing.

It is also the place where updated packages land first, so if you need an update that was released recently and that has not yet reached kali-rolling, you might be able to grab it from this repository. This is not recommended for regular users.

The Kali Linux Mirrors

TheĀ sources.listĀ extracts above refer toĀ http.kali.org: this is a server runningĀ Mirrorbits, which will redirect your HTTP requests to an official mirror close to you. Mirrorbits monitors each mirror to ensure that they are working and up-to-date; it will always redirect you to a good mirror.

Debugging a Mirror Redirection

If you have a problem with the mirror (for instance becauseĀ apt updateĀ fails), you can useĀ curl -sIĀ to see where you are being redirected:

$ curl -sI http://http.kali.org/README
HTTP/1.1 302 Found
Server: nginx
Date: Fri, 26 Jan 2024 06:05:36 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Cache-Control: private, no-cache
Link: <http://kali.download/kali/README>; rel=duplicate; pri=1; geo=ae
Link: <http://archive-4.kali.org/kali/README>; rel=duplicate; pri=2; geo=fr
Location: http://mirror.accuris.ca/kali/README

If the problem persists, you can editĀ /etc/apt/sources.listĀ and hardcode the name of another known working mirror in place of (or before) theĀ http.kali.orgĀ entry.

We also have a second Mirrorbits instance: whereĀ http.kali.orgĀ hosts the package repositories,Ā cdimage.kali.orgĀ hosts the released ISO images.

http://cdimage.kali.org/

If you want to request a list of official Kali Linux Mirrors, you can addĀ ?mirrorlistĀ to any valid URL pointing toĀ http.kali.orgĀ orĀ cdimage.kali.org.

http://http.kali.org/README?mirrorlist

http://cdimage.kali.org/README?mirrorlist

These lists are not exhaustive due to some Mirrorbits limitations (most notably mirrors restricted to some countries do not appear in the list unless you are in the given country). But they contain the best mirrors: they are well maintained and have large amounts of bandwidth available.

9.2. Basic Package Interaction

Armed with a basic understanding of the APT landscape, letā€™s take a look at some basic package interactions including the initialization of APT; installation, removal, and purging of packages; and upgrading of the Kali Linux system. Then letā€™s venture from the command line to take a look at some graphical APT tools.

9.2.1. Initializing APT

APT is a vast project and tool set, whose original plans included a graphical interface. From a client perspective, it is centered around the command-line toolĀ apt-getĀ as well asĀ apt, which was later developed to overcome design flaws ofĀ apt-get.

There are graphical alternatives developed by third parties, includingĀ synapticĀ andĀ aptitude, which we will discuss later. We tend to preferĀ apt, which we use in the examples that follow. We will, however, detail some of the major syntax differences between tools, as they arise.

When working with APT, you should first download the list of currently available packages withĀ apt update. Depending on the speed of your connection, this can take some time because various packagesā€™ list, sourcesā€™ list and translation files have grown in size alongside Kali development. Of course, CD/DVD-ROM installation sets install much more quickly, because they are local to your machine.

9.2.2. Installing Packages

Thanks to the thoughtful design of the Debian package system, you can install packages, with or without their dependencies, fairly easily. Letā€™s take a look at package installation withĀ dpkgĀ andĀ apt.

Installing Packages with dpkg

dpkgĀ is the core tool that you will use (either directly or indirectly through APT) when you need to install a package. It is also a go-to choice if you are operating offline, since it doesnā€™t require an Internet connection. Remember,Ā dpkgĀ will not install any dependencies that the package might require. To install a package withĀ dpkg, simply provide theĀ -iĀ orĀ --installĀ option and the path to theĀ .deb. This implies that you have previously downloaded (or obtained in some other way) theĀ .debĀ file of the package to install.

# dpkg -i man-db_2.9.3-2_amd64.deb
(Reading database ... 309317 files and directories currently installed.)
Preparing to unpack man-db_2.9.3-2_amd64.deb ...
Unpacking man-db (2.9.3-2) over (2.9.3-2) ...
Setting up man-db (2.9.3-2) ...
Updating database of manual pages ...
man-db.service is a disabled or a static unit not running, not starting it.
Processing triggers for kali-menu (2020.4.0) ...
Processing triggers for mime-support (3.64) ...

We can see the different steps performed byĀ dpkgĀ and can see at what point any error may have occurred. TheĀ -iĀ orĀ --installĀ option performs two steps automatically: it unpacks the package and runs the configuration scripts. You can perform these two steps independently (as apt does behind the scenes) with theĀ --unpackĀ andĀ --configureĀ options, respectively:

# dpkg --unpack man-db_2.9.3-2_amd64.deb
(Reading database ... 309317 files and directories currently installed.)
Preparing to unpack man-db_2.9.3-2_amd64.deb ...
Unpacking man-db (2.9.3-2) over (2.9.3-2) ...
Processing triggers for kali-menu (2020.4.0) ...
Processing triggers for mime-support (3.64) ...
# dpkg --configure man-db
Setting up man-db (2.9.3-2) ...
Updating database of manual pages ...

Note that the ā€œProcessing triggersā€ lines refer to code that is automatically executed whenever a package adds, removes, or modifies files in some monitored directories. For instance, theĀ mime-supportĀ package monitorsĀ /usr/lib/mime/packagesĀ and executes theĀ update-mimeĀ command whenever something changes in that directory (likeĀ /usr/lib/mime/packages/man-dbĀ in the specific case of man-db).

SometimesĀ dpkgĀ will fail to install a package and return an error. However, you can orderĀ dpkgĀ to ignore this and only issue a warning with variousĀ --force-*Ā options. Issuing theĀ dpkg --force-helpĀ command will display a complete list of these options. For example, you can useĀ dpkgĀ to forcibly installĀ zsh:

$ dpkg -i --force-overwrite zsh_5.8-5+b1_amd64.deb

A frequent error, which you are bound to encounter sooner or later, is a file collision. When a package contains a file that is already installed by another package,Ā dpkgĀ will refuse to install it. The following types of messages will then appear:

Unpacking libgdm (from .../libgdm_3.8.3-2_amd64.deb) ...
dpkg: error processing /var/cache/apt/archives/libgdm_3.8.3-2_amd64.deb (--unpack): trying to overwrite '/usr/bin/gdmflexiserver', which is also in package gdm3 3.4.1-9

In this case, if you think that replacing this file is not a significant risk to the stability of your system (which is usually the case), you can useĀ --force-overwriteĀ to overwrite the file.

While there are many availableĀ --force-*Ā options, onlyĀ --force-overwriteĀ is likely to be used regularly. These options exist for exceptional situations, and it is better to leave them alone as much as possible in order to respect the rules imposed by the packaging mechanism. Do not forget, these rules ensure the consistency and stability of your system.

Installing Packages with APT

Although APT is much more advanced thanĀ dpkgĀ and does a lot more behind the scenes, you will find that interacting with packages is quite simple. You can add a package to the system with a simpleĀ apt install package. APT will automatically install the necessary dependencies:

# apt install kali-tools-gpu
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  oclgausscrack truecrack
The following NEW packages will be installed:
Need to get 2,602 kB of archives.
After this operation, 2,898 kB of additional disk space will be used.
Get:1 http://kali.download/kali kali-rolling/main amd64 oclgausscrack amd64 1.3-1kali3 [30.7 kB]
Get:2 http://kali.download/kali kali-rolling/main amd64 truecrack amd64 3.6+git20150326-0kali1 [2,558 kB]
Get:3 http://kali.download/kali kali-rolling/main amd64 kali-tools-gpu amd64 2021.1.0 [12.6 kB]
Fetched 2,602 kB in 1s (2,645 kB/s)
Selecting previously unselected package oclgausscrack.
(Reading database ... 108127 files and directories currently installed.)
Preparing to unpack .../oclgausscrack_1.3-1kali3_amd64.deb ...
Unpacking oclgausscrack (1.3-1kali3) ...
Selecting previously unselected package truecrack.
Preparing to unpack .../truecrack_3.6+git20150326-0kali1_amd64.deb ...
Unpacking truecrack (3.6+git20150326-0kali1) ...
Selecting previously unselected package kali-tools-gpu.
Preparing to unpack .../kali-tools-gpu_2021.1.0_amd64.deb ...
Unpacking kali-tools-gpu (2021.1.0) ...
Setting up oclgausscrack (1.3-1kali3) ...
Setting up truecrack (3.6+git20150326-0kali1) ...
Setting up kali-tools-gpu (2021.1.0) ...
Processing triggers for man-db (2.9.3-2) ...
Processing triggers for kali-menu (2020.4.0) ...

You can also useĀ apt-get install package, orĀ aptitude install package. For simple package installation, they do essentially the same thing. As you will see later, the differences are more meaningful for upgrades or when dependencies resolution do not have any perfect solution.

IfĀ sources.listĀ lists several distributions, you can specify the package version withĀ apt install package=version, but indicating its distribution of origin (kali-rolling or kali-dev) withĀ apt install package/distributionĀ is usually preferred.

# apt install zsh=5.7.1-1
# apt install zsh/kali-dev

As withĀ dpkg, you can also instructĀ aptĀ to forcibly install a package and overwrite files withĀ --force-overwrite, but the syntax is a bit strange since you are passing the argument through toĀ dpkg:

# apt -o Dpkg::Options::="--force-overwrite" install zsh

9.2.3. Upgrading Kali Linux

As a rolling distribution, Kali Linux has spectacular upgrade capabilities. In this section, we will take a look at how simple it is to upgrade Kali, and we will discuss strategies for planning your updates.

We recommend regular upgrades, because they will install the latest security updates. To upgrade, useĀ apt updateĀ followed by eitherĀ apt upgrade,Ā apt-get upgrade, orĀ aptitude safe-upgrade. These commands look for installed packages that can be upgraded without removing any packages. In other words, the goal is to ensure the least intrusive upgrade possible. TheĀ apt-getĀ command line tool is slightly more demanding thanĀ aptitudeĀ orĀ aptĀ because it will refuse to install packages that were not installed beforehand.

TheĀ aptĀ tool will generally select the most recent version number.

To tellĀ aptĀ to use a specific distribution when searching for upgraded packages, you need to use theĀ -tĀ orĀ --target-releaseĀ option, followed by the name of the distribution you want (for example:Ā apt -t kali-rolling upgrade). To avoid specifying this option every time you useĀ apt, you can addĀ APT::Default-Release "kali-rolling";Ā in the fileĀ /etc/apt/apt.conf.d/local.

For more important upgrades, such as major version upgrades, useĀ apt full-upgrade. With this instruction,Ā aptĀ will complete the upgrade even if it has to remove some obsolete packages or install new dependencies. This is also the command that you should use for regular upgrades of your Kali Rolling system. It is so simple that it hardly needs explanation: APTā€™s reputation is based on this great functionality.

UnlikeĀ aptĀ andĀ aptitude,Ā apt-getĀ doesnā€™t know theĀ full-upgradeĀ command. Instead, you should useĀ apt-get dist-upgradeĀ (distribution upgrade), a well-known command thatĀ aptĀ andĀ aptitudeĀ also accept for backwards compatibility.

Be Aware of Important Changes

To anticipate some of these problems, you can install theĀ apt-listchangesĀ package, which displays information about possible problems at the beginning of a package upgrade. This information is compiled by the package maintainers and put inĀ /usr/share/doc/package/NEWS.DebianĀ files for your benefit. Reading these files (possibly throughĀ apt-listchanges) should help you avoid nasty surprises.

Since becoming a rolling distribution, Kali can receive upgrades several times a day. However, that might not be the best strategy. So, how often should you upgrade Kali Linux? There is no hard rule but there are some guidelines that can help you. You should upgrade:

  • When you are aware of a security issue that is fixed in an update.
  • When you suspect that an updated version might fix a bug that you are experiencing.
  • Before reporting a bug to make sure it is still present in the latest version that you have available.
  • Often enough to get the security fixes that you have not heard about.

There are also cases where it is best to not upgrade. For example, it might not be a good idea to upgrade:

  • If you canā€™t afford any breakage (for example, because you go offline, or because you are about to give a presentation with your computer); it is best to do the upgrade later, when you have enough time to troubleshoot any issue introduced in the process.
  • If a disruptive change happened recently (or is still ongoing) and you fear that all issues have not yet been discovered. For example, when a new GNOME version is released, not all packages are updated at the same time and you are likely to have a mix of packages with the old version and the new version. Most of the time this is fine and it helps everybody to release those updates progressively, but there are always exceptions and some applications might be broken due to such discrepancies.
  • If theĀ apt full-upgradeĀ output tells you that it will remove packages that you consider important for your work. In those cases, you want to review the situation and try to understand whyĀ aptĀ wants to remove them. Maybe the packages are currently broken and in this case you might want to wait until fixed versions are available, or they have been obsoleted and you should identify their replacements and then proceed with the full upgrade anyway.

In general, we recommend that you upgrade Kali at least once a week. You can certainly upgrade daily but it doesnā€™t make sense to do it more often than that. Even if our mirrors are synchronized four times a day, the updates coming from Debian usually land only once a day.

9.2.4. Removing and Purging Packages

Removing a package is even simpler than installing one. Letā€™s take a look at how to remove a package withĀ dpkgĀ andĀ apt.

To remove a package withĀ dpkg, supply theĀ -rĀ orĀ --removeĀ option, followed by the name of a package. This removal is not, however, complete: all of the configuration files, maintainer scripts, log files (system logs), data generated by the service (such as the content of an LDAP server directory or the content of a database for an SQL server), and most other user data handled by the package remain intact. The remove option makes it easy to uninstall a program and later re-install it with the same configuration. Also remember that dependencies are not removed. Consider this example:

# dpkg --remove kali-tools-gpu
(Reading database ... 108172 files and directories currently installed.)
Removing kali-tools-gpu (2021.1.0) ....

You can also remove packages from the system withĀ apt remove package. APT will automatically delete the packages that depend on the package that is being removed. Like theĀ dpkgĀ example, configuration files and user data will not be removed.

Through the addition of suffixes to package names, you can useĀ aptĀ (orĀ apt-getĀ andĀ aptitude) to install certain packages and remove others on the same command line. With anĀ apt installĀ command, add ā€œ-ā€ to the names of the packages you wish to remove. With anĀ apt removeĀ command, add ā€œ+ā€ to the names of the packages you wish to install.

The next example shows two different ways to installĀ package1Ā and to removeĀ package2.

# apt install package1 package2-
[...]
# apt remove package1+ package2
[...]

This can also be used to exclude packages that would otherwise be installed, for example due to aĀ RecommendsĀ (discussed later inĀ Recommends,Ā Suggests, andĀ EnhancesĀ Fields. In general, the dependency solver will use that information as a hint to look for alternative solutions.

To remove all data associated with a package, you can purge the package with theĀ dpkg -P package, orĀ apt purge packageĀ commands. This will completely remove the package and all user data, and in the case ofĀ apt, will delete dependencies as well.

# dpkg -r debian-cd
(Reading database ... 333606 files and directories currently installed.)
Removing debian-cd (3.1.32) ...
# dpkg -P debian-cd
(Reading database ... 332950 files and directories currently installed.)
Removing debian-cd (3.1.32) ...
Purging configuration files for debian-cd (3.1.32) ...

Warning! Given the definitive nature of purge, do not execute it lightly. You will lose everything associated with that package.

9.2.5. Inspecting Packages

Next, letā€™s take a look at some of the tools that can be used to inspect Debian packages. We will learn ofĀ dpkg,Ā apt, andĀ apt-cacheĀ commands that can be used to query and visualize the package database.

Querying dpkgā€™s Database and Inspecting .deb Files

We will begin with severalĀ dpkgĀ options that query the internal dpkg database. This database resides on the filesystem atĀ /var/lib/dpkgĀ and contains multiple sections including configuration scripts (/var/lib/dpkg/info), a list of files the package installed (/var/lib/dpkg/info/*.list), and the status of each package that has been installed (/var/lib/dpkg/status). You can useĀ dpkgĀ to interact with the files in this database. Note that most options are available in a long version (one or more relevant words, preceded by a double dash) and a short version (a single letter, often the initial of one word from the long version, and preceded by a single dash). This convention is so common that it is a POSIX standard.

First, letā€™s take a look atĀ --listfiles packageĀ (orĀ -L), which lists the files that were installed by the specified package:

$ dpkg -L base-passwd
/.
/usr
/usr/sbin
/usr/sbin/update-passwd
/usr/share
/usr/share/lintian
/usr/share/lintian/overrides
/usr/share/lintian/overrides/base-passwd
/usr/share/doc-base
/usr/share/doc-base/users-and-groups
/usr/share/base-passwd
/usr/share/base-passwd/group.master
/usr/share/base-passwd/passwd.master
/usr/share/man
/usr/share/man/pl
/usr/share/man/pl/man8
/usr/share/man/pl/man8/update-passwd.8.gz
[...]
/usr/share/doc
/usr/share/doc/base-passwd
/usr/share/doc/base-passwd/users-and-groups.txt.gz
/usr/share/doc/base-passwd/changelog.gz
/usr/share/doc/base-passwd/copyright
/usr/share/doc/base-passwd/README
/usr/share/doc/base-passwd/users-and-groups.html

Next,Ā dpkg --search fileĀ (orĀ -S), finds any packages containing the file or path passed in the argument. For example, to find the package containingĀ /bin/date:

$ dpkg -S /bin/date
coreutils: /bin/date

TheĀ dpkg --status packageĀ (orĀ -s) command displays the headers of an installed package. For example, to search the headers for theĀ coreutilsĀ package:

$ dpkg -s coreutils
Package: coreutils
Status: install ok installed
Priority: required
Section: utils
Installed-Size: 13855
Maintainer: Michael Stone
Architecture: amd64
Multi-Arch: foreign
Version: 8.23-3
Replaces: mktemp, realpath, timeout
Pre-Depends: libacl1 (>= 2.2.51-8), libattr1 (>= 1:2.4.46-8), libc6 (>= 2.17), libselinux1 (>= 2.1.13)
Conflicts: timeout
Description: GNU core utilities
This package contains the basic file, shell and text manipulation
utilities which are expected to exist on every operating system.
.
Specifically, this package includes:
arch base64 basename cat chcon chgrp chmod chown chroot cksum comm cp
csplit cut date dd df dir dircolors dirname du echo env expand expr
factor false flock fmt fold groups head hostid id install join link ln
logname ls md5sum mkdir mkfifo mknod mktemp mv nice nl nohup nproc numfmt
od paste pathchk pinky pr printenv printf ptx pwd readlink realpath rm
rmdir runcon sha*sum seq shred sleep sort split stat stty sum sync tac
tail tee test timeout touch tr true truncate tsort tty uname unexpand
uniq unlink users vdir wc who whoami yes
Homepage: http://gnu.org/software/coreutils

TheĀ dpkg --listĀ (orĀ -l) command displays the list of packages known to the system and their installation status. You can also useĀ grepĀ on the output to search for certain fields, or provide wildcards (such asĀ b*) to search for packages that match a particular partial search string. This will show a summary of the packages. For example, to show a summary list of all packages that start with ā€˜bā€™:

$ dpkg -l 'b*'
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name              Version       Architecture  Description
+++-=========================-==========================-============-=====================
ii  backdoor-factory  3.4.2+dfsg-4  all           Patch 32/64 bits ELF & win32/64 binaries with shellcode
un  backupninja           (no description available)
un  backuppc              (no description available)
un  balsa                 (no description available)
un  base                  (no description available)
[...]

TheĀ dpkg --contents file.debĀ (orĀ -c) command lists all the files in a particularĀ .debĀ file:

$ dpkg -c /var/cache/apt/archives/gpg_2.2.20-1_amd64.deb
drwxr-xr-x root/root         0 2020-03-23 15:05 ./
drwxr-xr-x root/root         0 2020-03-23 15:05 ./usr/
drwxr-xr-x root/root         0 2020-03-23 15:05 ./usr/bin/
-rwxr-xr-x root/root   1062832 2020-03-23 15:05 ./usr/bin/gpg
drwxr-xr-x root/root         0 2020-03-23 15:05 ./usr/share/
drwxr-xr-x root/root         0 2020-03-23 15:05 ./usr/share/doc/
drwxr-xr-x root/root         0 2020-03-23 15:05 ./usr/share/doc/gpg/
-rw-r--r-- root/root       677 2020-03-23 14:45 ./usr/share/doc/gpg/NEWS.Debian.gz
-rw-r--r-- root/root     24353 2020-03-23 15:05 ./usr/share/doc/gpg/changelog.Debian.gz
-rw-r--r-- root/root    384091 2020-03-20 11:38 ./usr/share/doc/gpg/changelog.gz
-rw-r--r-- root/root     10555 2020-03-23 15:04 ./usr/share/doc/gpg/copyright
drwxr-xr-x root/root         0 2020-03-23 15:05 ./usr/share/man/
drwxr-xr-x root/root         0 2020-03-23 15:05 ./usr/share/man/man1/
-rw-r--r-- root/root     46139 2020-03-23 15:05 ./usr/share/man/man1/gpg.1.gz

TheĀ dpkg --info file.debĀ (orĀ -I) command displays the headers of the specifiedĀ .debĀ file:

$ dpkg -I /var/cache/apt/archives/gpg_2.2.20-1_amd64.deb
 new Debian package, version 2.0.
 size 894224 bytes: control archive=1160 bytes.
    1219 bytes,    25 lines      control
     374 bytes,     6 lines      md5sums
 Package: gpg
 Source: gnupg2
 Version: 2.2.20-1
 Architecture: amd64
 Maintainer: Debian GnuPG Maintainers
 Installed-Size: 1505
 Depends: gpgconf (= 2.2.20-1), libassuan0 (>= 2.5.0), libbz2-1.0, libc6 (>= 2.25), libgcrypt20 (>= 1.8.0), libgpg-error0 (>= 1.35), libreadline8 (>= 6.0), libsqlite3-0 (>= 3.7.15), zlib1g (>= 1:1.1.4)
 Recommends: gnupg (= 2.2.20-1)
 Breaks: gnupg (<< 2.1.21-4)
 Replaces: gnupg (<< 2.1.21-4)
 Section: utils
 Priority: optional
 Multi-Arch: foreign
 Homepage: https://www.gnupg.org/
 Description: GNU Privacy Guard -- minimalist public key operations
  GnuPG is GNU's tool for secure communication and data storage.
  It can be used to encrypt data and to create digital signatures.
  It includes an advanced key management facility and is compliant
  with the proposed OpenPGP Internet standard as described in RFC4880.
[...]

You can also useĀ dpkgĀ to compare package version numbers with theĀ --compare-versionsĀ option, which is often called by external programs, including configuration scripts executed byĀ dpkgĀ itself. This option requires three parameters: a version number, a comparison operator, and a second version number. The different possible operators are:Ā ltĀ (strictly less than),Ā leĀ (less than or equal to),Ā eqĀ (equal),Ā neĀ (not equal),Ā geĀ (greater than or equal to), andĀ gtĀ (strictly greater than). If the comparison is correct,Ā dpkgĀ returns 0 (success); if not, it gives a non-zero return value (indicating failure). Consider these comparisons:

$ dpkg --compare-versions 1.2-3 gt 1.1-4
$ echo $?
0
$ dpkg --compare-versions 1.2-3 lt 1.1-4
$ echo $?
1
$ dpkg --compare-versions 2.6.0pre3-1 lt 2.6.0-1
$ echo $?
1

Note the unexpected failure of the last comparison: forĀ dpkg, the string ā€œpreā€ (usually denoting a pre-release) has no particular meaning, andĀ dpkgĀ simply interprets it as a string, in which case ā€œ2.6.0pre3-1ā€ is alphabetically greater than ā€œ2.6.0-1ā€. When we want a packageā€™s version number to indicate that it is a pre-release, we use the tilde character, ā€œ~ā€:

$ dpkg --compare-versions 2.6.0~pre3-1 lt 2.6.0-1
$ echo $?
0

Querying the Database of Available Packages withĀ apt-cacheĀ andĀ apt

TheĀ apt-cacheĀ command can display much of the information stored in APTā€™s internal database. This information is a sort of cache since it is gathered from the different sources listed in theĀ sources.listĀ file. This happens during theĀ apt updateĀ operation.

VOCABULARYĀ Cache

A cache is a temporary storage system used to speed up frequent data access when the usual access method is expensive (performance-wise). This concept can be applied in numerous situations and at different scales, from the core of microprocessors up to high-end storage systems.

In the case of APT, the referenceĀ PackagesĀ files are those located on Debian mirrors. That said, it would be very ineffective to push every search through the online package databases. That is why APT stores a copy of those files (inĀ /var/lib/apt/lists/) and searches are done within those local files. Similarly,Ā /var/cache/apt/archives/Ā contains a cached copy of already downloaded packages to avoid downloading them again if you need to reinstall them.

To avoid excessive disk usage when you upgrade frequently, you should regularly sort through theĀ /var/cache/apt/archives/Ā directory. Two commands can be used for this:Ā apt cleanĀ (orĀ apt-get clean) entirely empties the directory;Ā apt autocleanĀ (apt-get autoclean) only removes packages that can no longer be downloaded because they have disappeared from the mirror and are therefore useless. Note that the configuration parameterĀ APT::Clean-InstalledĀ can be used to prevent the removal ofĀ .debĀ files that are currently installed. Also, note thatĀ aptĀ drops the downloaded files once they have been installed, so this matters mainly when you use other tools.

TheĀ apt-cacheĀ command can do keyword-based package searches withĀ apt-cache search keyword. It can also display the headers of the packageā€™s available versions withĀ apt-cache show package. This command provides the packageā€™s description, its dependencies, and the name of its maintainer. This feature is particularly useful in determining the packages that are installed via metapackages, such asĀ kali-tools-wireless,Ā kali-tools-web, andĀ kali-tools-gpu. Note thatĀ apt search,Ā apt show,Ā aptitude search, andĀ aptitude showĀ work in the same way.

An Alternative:Ā axi-cache

apt-cache searchĀ is a very rudimentary tool, basically implementingĀ grepĀ on packageā€™s descriptions. It often returns too many results or none at all, when too many keywords are included.

axi-cache search term, on the other hand, provides better results, sorted by relevancy. It uses theĀ XapianĀ search engine and is part of theĀ apt-xapian-indexĀ package, which indexes all package information (and more, like theĀ .desktopĀ files from all Debian packages). It knows about tags and returns results in a matter of milliseconds.

$ axi-cache search forensics graphical
7 results found.
Results 1-7:
100% autopsy - graphical interface to SleuthKit
94% forensics-all-gui - Debian Forensics Environment - GUI components (metapackage)
87% forensics-extra-gui - Forensics Environment - extra GUI components (metapackage)
86% forensics-colorize - show differences between files using color graphics
44% gpart - Guess PC disk partition table, find lost partitions
39% testdisk - Partition scanner and disk recovery tool, and PhotoRec file recovery tool
8% texlive-publishers - TeX Live: Publisher styles, theses, etc.
More terms: tools experts autopsy picture ethical pentesters hackers
More tags: admin::forensics security::forensics admin::recovery interface::commandline admin::boot scope::utility role::program

Some features are more rarely used. For instance,Ā apt-cache policyĀ displays the priorities of package sources as well as those of individual packages. Another example isĀ apt-cache dumpavail, which displays the headers of all available versions of all packages.Ā apt-cache pkgnamesĀ displays the list of all the packages that appear at least once in the cache.

9.2.6. Troubleshooting

Sooner or later, you will run into a problem when interacting with a package. In this section, we will outline some basic troubleshooting steps that you can take and provide some tools that will lead you closer to a potential solution.

Handling Problems after an Upgrade

In spite of the Debian or Kali maintainersā€™ best efforts, a system upgrade isnā€™t always as smooth as we would hope. New software versions may be incompatible with previous ones (for instance, their default behavior or their data format may have changed), or bugs may slip through the cracks despite the testing performed by package maintainers and Debian Unstable users.

Leveraging Bug Reports

You might sometimes find that a new version of software doesnā€™t work at all. This generally happens if the application isnā€™t particularly popular and hasnā€™t been tested enough. The first thing to do is to have a look at theĀ Kali bug trackerĀ and at theĀ Debian bug tracking systemĀ atĀ https://bugs.debian.org/package, and check whether the problem has already been reported. If it hasnā€™t, you should report it yourself (seeĀ Filing a Good Bug ReportĀ for detailed instructions). If it is already known, the bug report and the associated messages are usually an excellent source of information related to the bug. In some cases, a patch already exists and has been made available in the bug report itself; you can then recompile a fixed version of the broken package locally (seeĀ Modifying Kali Packages). In other cases, users may have found a workaround for the problem and shared their insights about it in their replies to the report; those instructions may help you work around the problem until a fix or patch is released. In a best-case scenario, the package may have already been fixed and you may find details in the bug report.

Downgrading to a Working Version

When the problem is a clear regression (where the former version worked), you can try to downgrade the package. In this case, you will need a copy of the old version. If you have access to the old version in one of the repositories configured in APT, you can use a simple one-liner command to downgrade (seeĀ Installing Packages with APT). But with Kaliā€™s rolling release, you will usually only find a single version of each package at any one time.

You can still try to find the oldĀ .debĀ file and install it manually withĀ dpkg. OldĀ .debĀ files can be found in multiple places:

  • In APTā€™s cache inĀ /var/cache/apt/archives/.
  • In theĀ poolĀ directory on your usual Kali mirror (removed and obsolete packages are kept for three to four days to avoid problems with users not having the latest package indices).
  • InĀ https://snapshot.debian.orgĀ if the affected package was provided by Debian and not by Kali; this service keeps historical versions of all Debian packages.
Dealing with Broken Maintainer Scripts

Sometimes the upgrade gets interrupted because one of the package maintainer scripts fails (usually, it is theĀ postinst). In those cases, you can try to diagnose the problem, and possibly work around it, by editing the problematic script.

Here we rely on the fact that maintainer scripts are stored inĀ /var/lib/dpkg/info/Ā and that we can review and modify them.

Since maintainer scripts are usually simple shell scripts, it is possible to add aĀ set -xĀ line just after the shebang line and arrange them to be rerun (withĀ dpkg --configure -aĀ forĀ postinst) to see precisely what is happening and where it is failing. This output can also nicely complement any bug report that you might file.

With this newly gained knowledge, you can either fix the underlying problem or transform the failing command into a working one (for example by addingĀ || trueĀ at the end of the line).

Note that this tip does not work for a failingĀ preinstĀ since that script is executed even before the package gets installed so it is not yet in its final location. It does work forĀ postrmĀ andĀ prermĀ although you will need to execute a package removal (respectively upgrade) to trigger them.

The dpkg Log File

TheĀ dpkgĀ tool keeps a log of all of its actions inĀ /var/log/dpkg.log. This log is extremely verbose, since it details all the stages of each package. In addition to offering a way to track dpkgā€™s behavior, it helps to keep a history of the development of the system: you can find the exact moment when each package has been installed or updated, and this information can be extremely useful in understanding a recent change in behavior. Additionally, with all versions being recorded, it is easy to cross-check the information with theĀ changelog.Debian.gzĀ for packages in question, or even with online bug reports.

# tail /var/log/dpkg.log
2021-01-06 23:16:37 status installed kali-tools-gpu:amd64 2021.1.0
2021-01-06 23:16:37 remove kali-tools-gpu:amd64 2021.1.0
2021-01-06 23:16:37 status half-configured kali-tools-gpu:amd64 2021.1.0
2021-01-06 23:16:37 status half-installed kali-tools-gpu:amd64 2021.1.0
2021-01-06 23:16:37 status config-files kali-tools-gpu:amd64 2021.1.0
2021-01-06 23:16:37 status not-installed kali-tools-gpu:amd64

Reinstalling Packages with apt ā€”reinstall and aptitude reinstall

When you mistakenly damage your system by removing or modifying certain files, the easiest way to restore them is to reinstall the affected package. Unfortunately, the packaging system finds that the package is already installed and politely refuses to reinstall it. To avoid this, use theĀ --reinstallĀ option of theĀ aptĀ andĀ apt-getĀ commands. The following command reinstallsĀ postfixĀ even if it is already present:

# apt --reinstall install postfix

TheĀ aptitudeĀ command line is slightly different but achieves the same result withĀ aptitude reinstall postfix. TheĀ dpkgĀ command does not prevent re-installation, but it is rarely called directly.

Do Not UseĀ apt --reinstallĀ to Recover from an Attack

UsingĀ apt --reinstallĀ to restore packages modified during an attack will certainly not recover the system as it was.

After an attack, you canā€™t rely on anything:Ā dpkgĀ andĀ aptĀ might have been replaced by malicious programs, not reinstalling the files as you would like them to. The attacker might also have altered or created files outside the control ofĀ dpkg.

Remember that you can specify a specific distribution withĀ aptĀ as well, which means you can roll back to an older version of a package (if for instance you know that it works well), provided that it is still available in one of the sources referenced by theĀ sources.listĀ file:

# apt install w3af/kali-dev

Leveraging ā€”force-* to Repair Broken Dependencies

If you are not careful, the use of aĀ --force-*Ā option or some other malfunction can lead to a system where the APT family of commands will refuse to function. In effect, some of these options allow installation of a package when a dependency is not met, or when there is a conflict. The result is an inconsistent system from the point of view of dependencies, and the APT commands will refuse to execute any action except those that will bring the system back to a consistent state (this often consists of installing the missing dependency or removing a problematic package). This usually results in a message like this one, obtained after installing a new version ofĀ rdesktopĀ while ignoring its dependency on a newer version ofĀ libc6:

# apt full-upgrade
[...]
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
rdesktop: Depends: libc6 (>= 2.14) but 2.3.6.ds1-13etch7 is installed
E: Unmet dependencies. Try using -f.

If you are a courageous administrator who is certain of the correctness of your analysis, you may choose to ignore a dependency or conflict and use the correspondingĀ --force-*Ā option. In this case, if you want to be able to continue to useĀ aptĀ orĀ aptitude, you must editĀ /var/lib/dpkg/statusĀ to delete or modify the dependency, or conflict, that you have chosen to override.

This manipulation is an ugly hack and should never be used, except in the most extreme case of necessity. Quite frequently, a more fitting solution is to recompile the package that is causing the problem or use a new version (potentially corrected) from a repository providing backports (backports are newer versions especially recompiled to work in an older environment).

9.2.7. Frontends: aptitude and synaptic

APT is a C++ program whose code mainly resides in theĀ libapt-pkgĀ shared library. Thanks to this shared library, it opened the door for the creation of user interfaces (front-ends), since the shared library code can easily be reused. Historically,Ā apt-getĀ was only designed as a test front-end forĀ libapt-pkgĀ but its success tends to obscure this fact.

Over time, despite the popularity of command line interfaces likeĀ aptĀ andĀ apt-get, various graphical interfaces were developed. We will take a look at two of those interfaces in this section:Ā aptitudeĀ andĀ synaptic.

Aptitude

Aptitude, shown in Figure 1, is an interactive program that can be used in semi-graphical mode on the console. You can browse the list of installed and available packages, look up all the information, and select packages to install or remove. The program is designed specifically to be used by administrators so its default behavior is much more intelligent than APTā€™s, and its interface much easier to understand.

Figure 1: The aptitude package manager

Figure 1: The aptitude package manager

When you runĀ aptitude, you are shown a list of packages sorted by state (installed, not-installed, or installed but not available on the mirrors), while other sections display tasks, virtual packages, and new packages that appeared recently on mirrors. To facilitate thematic browsing, other views are available.

In all cases,Ā aptitudeĀ displays a list combining categories and packages on the screen. Categories are organized through a tree structure, whose branches can respectively be unfolded or folded with theĀ Enter,Ā [+, andĀ ]+Ā keys. TheĀ +Ā key should be used to mark a package for installation,Ā -Ā to mark it for removal, andĀ _Ā to purge it. Note that these keys can also be used for categories, in which case the corresponding actions will be applied to all the packages of the category. TheĀ uĀ key updates the lists of available packages and ** +Shift+ +u** prepares a global system upgrade. TheĀ gĀ key switches to a summary view of the requested changes (and typingĀ gĀ again will apply the changes), andĀ qĀ quits the current view. If you are in the initial view, this will closeĀ aptitude.

aptitudeā€™s Documentation

This section does not cover the finer details of usingĀ aptitude, it rather focuses on giving you a user survival kit.Ā aptitudeĀ is rather well documented and we advise you to use its complete manual available in theĀ aptitude-doc-enĀ package (seeĀ /usr/share/doc/aptitude/html/en/index.html) or at:

https://www.debian.org/doc/manuals/aptitude/

To search for a package, you can typeĀ /Ā followed by a search pattern. This pattern matches the name of the package but can also be applied to the description (if preceded byĀ ~d), to the section (withĀ ~s), or to other characteristics detailed in the documentation. The same patterns can filter the list of displayed packages: type theĀ lĀ key (as inĀ limit) and enter the pattern.

Managing theĀ automatic flagĀ of Debian packages (seeĀ Tracking Automatically Installed Packages) is a breeze withĀ aptitude. It is possible to browse the list of installed packages and mark packages as automatic withĀ Shift+mĀ or you can remove the mark with theĀ mĀ key. Automatic packages are displayed with an ā€œAā€ in the list of packages. This feature also offers a simple way to visualize the packages in use on a machine, without all the libraries and dependencies that you donā€™t really care about. The related pattern that can be used withĀ lĀ (to activate the filter mode) isĀ ~i!~M. It specifies that you only want to see installed packages (~i) not marked as automatic (!~M).

UsingĀ aptitudeĀ on the Command-Line Interface

Most of Aptitudeā€™s features are accessible via the interactive interface as well as via the command-line. These command-lines will seem familiar to regular users ofĀ apt-getĀ andĀ apt-cache.

The advanced features ofĀ aptitudeĀ are also available on the command-line. You can use the same package search patterns as in the interactive version. For example, if you want to clean up the list of manually installed packages, and if you know that none of the locally installed programs require any particular libraries or Perl modules, you can mark the corresponding packages as automatic with a single command:

# aptitude markauto '~slibs|~sperl'

Here, you can clearly see the power of the search pattern system ofĀ aptitude, which enables the instant selection of all the packages in theĀ libsĀ andĀ perlĀ sections.

Beware, if some packages are marked as automatic and if no other package depends on them, they will be removed immediately (after a confirmation request).

Managing Recommendations, Suggestions, and Tasks

Another interesting feature ofĀ aptitudeĀ is the fact that it respects recommendations between packages while still giving users the choice not to install them on a case-by-case basis. For example, theĀ gnomeĀ package recommendsĀ gdebiĀ (among others). When you select the former for installation, the latter will also be selected (and marked as automatic if not already installed on the system). TypingĀ gĀ will make it obvious:Ā gdebiĀ appears on the summary screen of pending actions in the list of packages installed automatically to satisfy dependencies. However, you can decide not to install it by deselecting it before confirming the operations.

Note that this recommendation tracking feature does not apply to upgrades. For instance, if a new version ofĀ gnomeĀ recommends a package that it did not recommend formerly, the package wonā€™t be marked for installation. However, it will be listed on the upgrade screen so that the administrator can still select it for installation.

Suggestions between packages are also taken into account, but in a manner adapted to their specific status. For example, sinceĀ gnomeĀ suggestsĀ dia-gnome, the latter will be displayed on the summary screen of pending actions (in the section of packages suggested by other packages). This way, it is visible and the administrator can decide whether to take the suggestion into account or not. Since it is only a suggestion and not a dependency or a recommendation, the package will not be selected automaticallyā€”its selection requires manual intervention (thus, the package will not be marked as automatic).

In the same spirit, remember thatĀ aptitudeĀ makes intelligent use of the concept of tasks. Since tasks are displayed as categories in the screens of packages lists, you can either select a full task for installation or removal or browse the list of packages included in the task to select a smaller subset.

Better Solver Algorithms

To conclude this section, letā€™s note thatĀ aptitudeĀ has more elaborate algorithms compared toĀ aptĀ when it comes to resolving difficult situations. When a set of actions is requested and when these combined actions would lead to an incoherent system,Ā aptitudeĀ evaluates several possible scenarios and presents them in order of decreasing relevance. However, these algorithms are not foolproof. Fortunately, there is always the possibility to manually select the actions to perform. When the currently selected actions lead to contradictions, the upper part of the screen indicates a number of broken packages (you can directly navigate to those packages by pressingĀ b). Then you can manually build a solution. In particular, you can get access to the different available versions by selecting the package withĀ Enter. If the selection of one of these versions solves the problem, you should not hesitate to use the function. When the number of broken packages gets down to zero, you can safely go to the summary screen of pending actions for a last check before you apply them.

Aptitudeā€™s Log

LikeĀ dpkg,Ā aptitudeĀ keeps a trace of executed actions in its logfile (/var/log/aptitude). However, since both commands work at a very different level, you cannot find the same information in their respective logfiles. WhileĀ dpkgĀ logs all the operations executed on individual packages step-by-step,Ā aptitudeĀ gives a broader view of high-level operations like a system-wide upgrade.

Beware, this logfile only contains a summary of operations performed byĀ aptitude. If other front-ends (or evenĀ dpkgĀ itself) are occasionally used, thenĀ aptitudeā€™s log will only contain a partial view of the operations, so you canā€™t rely on it to build a trustworthy history of the system.

Synaptic

Synaptic is a graphical package manager that features a clean and efficient graphical interface (shown in Figure 2) based on GTK+. Its many ready-to-use filters give fast access to newly available packages, installed packages, upgradable packages, obsolete packages, and so on. If you browse through these lists, you can select the operations to be done on the packages (install, upgrade, remove, purge); these operations are not performed immediately, but put into a task list. A single click on a button then validates the operations and they are performed in one go.

Figure 2: synaptic Package Manager

Figure 2: synaptic Package Manager

9.3. Advanced APT Configuration and Usage

Now it is time to dive into some more advanced topics. First, we will take a look at advanced configuration of APT, which will allow you to set more permanent options that will apply to APT tools. We will then show how package priorities can be manipulated, which opens the door for advanced fine-tuned, customized updates and upgrades. We will also show how to handle multiple distributions so that you can start experimenting with packages coming from other distributions. Next, we will take a look at how to track automatically installed packages, a capability that enables you to manage packages that are installed through dependencies. We will also explain how multi-arch support opens the door for running packages built for various hardware architectures. Last but not least, we will discuss the cryptographic protocols and utilities in place that will let you validate each packageā€™s authenticity.

9.3.1. Configuring APT

Before we dive into the configuration of APT, letā€™s take a moment to discuss the configuration mechanism of a Debian-based system. Historically, configuration was handled by dedicated configuration files. However, in modern Linux systems like Debian and Kali, configuration directories with theĀ .dĀ suffix are becoming more commonly used. Each directory represents a configuration file that is split into multiple files. In this sense, all of the files inĀ /etc/apt/apt.conf.d/Ā are instructions for the configuration of APT. APT processes the files in alphabetical order, so that the later files can modify configuration elements defined in the earlier files.

This structure brings some flexibility to administrators and package maintainers, allowing them to make software configuration changes through file additions without having to change an existing file. This is especially helpful for package maintainers because they can use this approach to adapt the configuration of other software to ensure that it perfectly co-exists with theirs, without breaking the Debian policy that explicitly forbids modifying configuration files of other packages. Because of theĀ .dĀ configuration mechanism, you donā€™t have to manually follow multiple package configuration instructions typically found in the packageā€™sĀ /usr/share/doc/package/README.DebianĀ file, since the installer can drop in configuration files.

Beware of Configuration Files Generated fromĀ .dĀ Directories

While APT has native support of itsĀ /etc/apt/apt.conf.dĀ directory, this is not always the case. For some applications (like exim, for example), theĀ .dĀ directory is a Debian-specific addition used as input to dynamically generate the canonical configuration file used by the application. In those cases, the packages provide an ā€œupdate-*ā€ command (for example:Ā update-exim4.conf) that will concatenate the files from theĀ .dĀ directory and overwrite the main configuration file.

In those cases, you must not manually edit the main configuration file as your changes will be lost on the next execution of theĀ update-*Ā command, and you must also not forget to run the former command after having edited a file out of theĀ .dĀ directory (or your changes will not be used).

Armed with an understanding of theĀ .dĀ configuration mechanism, letā€™s talk about how you can leverage it to configure APT. As we have discussed, you can alter APTā€™s behavior through command-line arguments toĀ dpkgĀ like this example, which performs a forced overwrite install ofĀ zsh:

# apt -o Dpkg::Options::="--force-overwrite" install zsh

Obviously this is very cumbersome, especially if you use options frequently, but you can also use theĀ .dĀ directory configuration structure to configure certain aspects of APT by adding directives to a file in theĀ /etc/apt/apt.conf.d/Ā directory. For example, this (and any other) directive can easily be added to a file inĀ /etc/apt/apt.conf.d/. The name of this file is somewhat arbitrary, but a common convention is to use eitherĀ localĀ orĀ 99local:

$ cat /etc/apt/apt.conf.d/99local
Dpkg::Options {
   "--force-overwrite";
}

There are many other helpful configuration options and we certainly canā€™t cover them all, but one we will touch on involves network connectivity. For example, if you can only access the web through a proxy, add a line likeĀ Acquire::http::proxy "http://yourproxy:3128". For an FTP proxy, useĀ Acquire::ftp::proxy "ftp://yourproxy".

To discover more configuration options, read the apt.conf(5) manual page with theĀ man apt.confĀ command (for details on manual pages, seeĀ Manual Pages).

9.3.2. Managing Package Priorities

One of the most important aspects in the configuration of APT is the management of the priorities associated with each package source. For instance, you might want to extend your Kali Linux system with one or two newer packages from Debian Unstable or Debian Experimental. It is possible to assign a priority to each available package (the same package can have several priorities depending on its version or the distribution providing it). These priorities will influence APTā€™s behavior: for each package, it will always select the version with the highest priority (except if this version is older than the installed one and its priority is less than 1000).

APT defines several default priorities. Each installed package version has a priority of 100. A non-installed version has a priority of 500 by default but it can jump to 990 if it is part of the target release (defined with theĀ -tĀ command-line option or theĀ APT::Default-ReleaseĀ configuration directive).

You can modify the priorities by adding entries in theĀ /etc/apt/preferencesĀ file with the names of the affected packages, their version, their origin and their new priority.

APT will never install an older version of a package (that is, a package whose version number is lower than the one of the currently installed package) except when its priority is higher than 1000. APT will always install the highest priority package that follows this constraint. If two packages have the same priority, APT installs the newest one (whose version number is the highest). If two packages of same version have the same priority but differ in their content, APT installs the version that is not installed (this rule has been created to cover the case of a package update without the increment of the revision number, which is usually required).

In more concrete terms, a package whose priority is less than 0 will never be installed. A package with a priority ranging between 0 and 100 will only be installed if no other version of the package is already installed. With a priority between 100 and 500, the package will only be installed if there is no other newer version installed or available in another distribution. A package of priority between 501 and 990 will only be installed if there is no newer version installed or available in the target distribution. With a priority between 990 and 1000, the package will be installed except if the installed version is newer. A priority greater than 1000 will always lead to the installation of the package even if it forces APT to downgrade to an older version.

When APT checksĀ /etc/apt/preferences, it first takes into account the most specific entries (often those specifying the concerned package), then the more generic ones (including for example all the packages of a distribution). If several generic entries exist, the first match is used. The available selection criteria include the packageā€™s name and the source providing it. Every package source is identified by the information contained in aĀ ReleaseĀ file that APT downloads together with theĀ PackagesĀ files. These files specify the origin, usually ā€œKaliā€ for the packages from Kaliā€™s official mirrors and ā€œDebianā€ for the packages from Debianā€™s official mirrors, but the origin can also be a personā€™s or an organizationā€™s name for third-party repositories. TheĀ ReleaseĀ file also provides the name of the distribution together with its version. Letā€™s have a look at its syntax through some realistic case studies of this mechanism.

Priority of Kali-Bleeding-Edge and Debian Experimental

If you listed Debian experimental in yourĀ sources.listĀ file, the corresponding packages will almost never be installed because their default APT priority is 1. This is of course a specific case, designed to keep users from installing experimental packages by mistake. The packages can only be installed by typingĀ apt install package/experimental, assuming of course that you are aware of the risks and potential headaches of life on the edge. It is still possible (thoughĀ notĀ recommended) to treat packages of experimental like those of other distributions by giving them a priority of 500. This is done with a specific entry inĀ /etc/apt/preferences:

Package: *
Pin: release a=experimental
Pin-Priority: 500

Letā€™s suppose that you only want to use packages from Kali and that you only want Debian packages installed when explicitly requested. You could write the following entries in theĀ /etc/apt/preferencesĀ file (or in any file inĀ /etc/apt/preferences.d/):

Package: *
Pin: release o=Kali
Pin-Priority: 900

Package: *
Pin: release o=Debian
Pin-Priority: -10

In the last two examples, you have seenĀ a=experimental, which defines the name of the selected distribution andĀ o=KaliĀ andĀ o=Debian, which limit the scope to packages whose origin are Kali and Debian, respectively.

Letā€™s now assume that you have a server with several local programs depending on the version 5.22 of Perl and that you want to ensure that upgrades will not install another version of it. You could use this entry:

Package: perl
Pin: version 5.22*
Pin-Priority: 1001

The reference documentation for this configuration file is available in the manual page apt_preferences(5), which you can display withĀ man apt_preferences.

Adding Comments inĀ /etc/apt/preferences

There is no official syntax for comments inĀ /etc/apt/preferences, but some textual descriptions can be provided by prepending one or moreĀ ExplanationĀ fields into each entry:

Explanation: The package xserver-xorg-video-intel provided
Explanation: in experimental can be used safely
Package: xserver-xorg-video-intel
Pin: release a=experimental
Pin-Priority: 500

9.3.3. Working with Several Distributions

Given thatĀ aptĀ is such a marvelous tool, you will likely want to dive in and start experimenting with packages coming from other distributions. For example, after installing a Kali Rolling system, you might want to try out a software package available in Kali Dev, Debian Unstable, or Debian Experimental without diverging too much from the systemā€™s initial state.

Even if you will occasionally encounter problems while mixing packages from different distributions,Ā aptmanages such coexistence very well and limits risks very effectively (provided that the package dependencies are accurate). First, list all distributions used inĀ /etc/apt/sources.listĀ and define your reference distribution with theĀ APT::Default-ReleaseĀ parameter (seeĀ Upgrading Kali Linux).

Letā€™s suppose that Kali Rolling is your reference distribution but that Kali Dev and Debian Unstable are also listed in yourĀ sources.listĀ file. In this case, you can useĀ apt install package/unstableĀ to install a package from Debian Unstable. If the installation fails due to some unsatisfiable dependencies, let it solve those dependencies within Unstable by adding theĀ -t unstableĀ parameter.

In this situation, upgrades (upgradeĀ andĀ full-upgrade) are done within Kali Rolling except for packages already upgraded to another distribution: those will follow updates available in the other distributions. We will explain this behavior with the help of the default priorities set by APT below. Do not hesitate to useĀ apt-cache policyĀ (seeĀ Using apt-cache policy) to verify the given priorities.

Everything relies on the fact that APT only considers packages of higher or equal version than the installed package (assuming thatĀ /etc/apt/preferencesĀ has not been used to force priorities higher than 1000 for some packages).

UsingĀ apt-cacheĀ policy

To gain a better understanding of the mechanism of priority, do not hesitate to executeĀ apt-cache policyĀ to display the default priority associated with each package source. You can also useĀ apt-cache policy packageĀ to display the priorities of all available versions of a given package.

Letā€™s assume that you have installed version 1 of a first package fromĀ Kali RollingĀ and that version 2 and 3 are available respectively inĀ Kali DevĀ andĀ Debian Unstable. The installed version has a priority of 100 but the version available inĀ Kali RollingĀ (the very same) has a priority of 990 (because it is part of the target release). Packages inĀ Kali DevĀ andĀ Debian UnstableĀ have a priority of 500 (the default priority of a non-installed version). The winner is thus version 1 with a priority of 990. The package stays inĀ Kali Rolling.

Letā€™s take the example of another package whose version 2 has been installed fromĀ Kali Dev. Version 1 is available inĀ Kali RollingĀ and version 3 inĀ Debian Unstable. Version 1 (of priority 990ā€”thus lower than 1000) is discarded because it is lower than the installed version. This only leaves version 2 and 3, both of priority 500. Faced with this alternative, APT selects the newest version, the one fromĀ Debian Unstable. If you donā€™t want a package installed fromĀ Kali DevĀ to migrate toĀ Debian Unstable, you have to assign a priority lower than 500 (490 for example) to packages coming fromĀ Debian Unstable. You can modifyĀ /etc/apt/preferencesĀ to this effect:

Package: *
Pin: release a=unstable
Pin-Priority: 490

9.3.4. Tracking Automatically Installed Packages

One of the essential functionalities ofĀ aptĀ is the tracking of packages installed only through dependencies. These packages are calledĀ automaticĀ and often include libraries.

With this information, when packages are removed, the package managers can compute a list of automatic packages that are no longer needed (because there are no manually installed packages depending on them). The commandĀ apt autoremoveĀ will get rid of those packages. Aptitude does not have this command because it removes them automatically as soon as they are identified. In all cases, the tools display a clear message listing the affected packages.

It is a good habit to mark as automatic any package that you donā€™t need directly so that they are automatically removed when they arenā€™t necessary anymore. You can useĀ apt-mark auto packageĀ to mark the given package as automatic, whereasĀ apt-mark manual packageĀ does the opposite.Ā aptitude markautoĀ andĀ aptitude unmarkautoĀ work in the same way, although they offer more features for marking many packages at once (seeĀ Aptitude). The console-based interactive interface ofĀ aptitudeĀ also makes it easy to review the automatic flag on many packages.

You might want to know why an automatically installed package is present on the system. To get this information from the command line, you can useĀ aptitude why packageĀ (aptĀ andĀ apt-getĀ have no similar feature):

$ aptitude why python-debian
i   aptitude         Recommends apt-xapian-index
i A apt-xapian-index Depends    python-debian (>= 0.1.15)

9.3.5. Leveraging Multi-Arch Support

All Debian packages have anĀ ArchitectureĀ field in their control information. This field can contain either ā€œallā€ (for packages that are architecture-independent) or the name of the architecture that it targets (like amd64, or armhf). In the latter case, by default,Ā dpkgĀ will only install the package if its architecture matches the hostā€™s architecture as returned byĀ dpkg --print-architecture.

This restriction ensures that you do not end up with binaries compiled for an incorrect architecture. Everything would be perfect except that (some) computers can run binaries for multiple architectures, either natively (an amd64 system can run i386 binaries) or through emulators.

Enabling Multi-Arch

Multi-arch support forĀ dpkgĀ allows users to define foreign architectures that can be installed on the current system. This is easily done withĀ dpkg --add-architecture, as in the example below where the i386 architecture needs to be added to the amd64 system in order to run Microsoft Windows applications usingĀ Wine. There is a correspondingĀ dpkg --remove-architectureĀ to drop support of a foreign architecture, but it can only be used when no packages of this architecture remain installed.

# dpkg --print-architecture
amd64
# wine
it looks like wine32 is missing, you should install it.
multiarch needs to be enabled first.  as root, please
execute "dpkg --add-architecture i386 & apt-get update &
apt-get install wine32"
Usage: wine PROGRAM [ARGUMENTS...]   Run the specified program
       wine --help                   Display this help and exit
       wine --version                Output version information and exit
# dpkg --add-architecture i386
# dpkg --print-foreign-architectures
i386
# apt update
[...]
# apt install wine32
[...]
Setting up libwine:i386 (1.8.6-5) ...
Setting up vdpau-driver-all:i386 (1.1.1-6) ...
Setting up wine32:i386 (1.8.6-5) ...
Setting up libasound2-plugins:i386 (1.1.1-1) ...
Processing triggers for libc-bin (2.24-9)
# wine
Usage: wine PROGRAM [ARGUMENTS...]   Run the specified program
     wine --help                   Display this help and exit
     wine --version                Output version information and exit
# dpkg --remove-architecture i386
dpkg: error: cannot remove architecture 'i386' currently in use by the database
# dpkg --print-foreign-architectures
i386

APT will automatically detect when dpkg has been configured to support foreign architectures and will start downloading the correspondingĀ PackagesĀ files during its update process.

Foreign packages can then be installed withĀ apt install package:architecture.

Using Proprietary i386 Binaries on amd64

There are multiple use cases for multi-arch, but the most popular one is the possibility to execute 32-bit binaries (i386) on 64-bit systems (amd64), in particular since several popular proprietary applications (like Skype) are only provided in 32-bit versions.

To make multi-arch actually useful and usable, libraries had to be repackaged and moved to an architecture-specific directory so that multiple copies (targeting different architectures) can be installed alongside one another. Such updated packages contain theĀ Multi-Arch: sameĀ header field to tell the packaging system that the various architectures of the package can be safely co-installed (and that those packages can only satisfy dependencies of packages of the same architecture).

$ dpkg -s libwine
dpkg-query: error: --status needs a valid package name but 'libwine' is not: ambiguous package name 'libwine' with more than one installed instance

Use --help for help about querying packages.
$ dpkg -s libwine:amd64 libwine:i386 | grep ^Multi
Multi-Arch: same
Multi-Arch: same
$ dpkg -L libgcc1:amd64 | grep .so
[...]
/usr/lib/x86_64-linux-gnu/wine/libwine.so.1
$ dpkg -S /usr/share/doc/libwine/copyright
libwine:amd64, libwine:i386: /usr/share/doc/libwine/copyright

It is worth noting thatĀ Multi-Arch: sameĀ packages must have their names qualified with their architecture to be unambiguously identifiable. These packages may also share files with other instances of the same package;Ā dpkgĀ ensures that all packages have bit-for-bit identical files when they are shared. Also, all instances of a package must have the same version, therefore they must be upgraded together.

Multi-Arch support also brings some interesting challenges in the way dependencies are handled. Satisfying a dependency requires either a package markedĀ Multi-Arch: foreignĀ or a package whose architecture matches the one of the package declaring the dependency (in this dependency resolution process, architecture-independent packages are assumed to be of the same architecture as the host). A dependency can also be weakened to allow any architecture to fulfill it, with theĀ package:anyĀ syntax, but foreign packages can only satisfy such a dependency if they are markedĀ Multi-Arch: allowed.

9.3.6. Validating Package Authenticity

System upgrades are very sensitive operations and you really want to ensure that you only install official packages from the Kali repositories. If the Kali mirror you are using has been compromised, a computer cracker could try to add malicious code to an otherwise legitimate package. Such a package, if installed, could do anything the cracker designed it to do including disclose passwords or confidential information. To circumvent this risk, Kali provides a tamper-proof seal to guaranteeā€”at install timeā€”that a package really comes from its official maintainer and hasnā€™t been modified by a third party.

The seal works with a chain of cryptographic hashes and a signature. The signed file is theĀ ReleaseĀ file, provided by the Kali mirrors. It contains a list of theĀ PackagesĀ files (including their compressed forms,Ā Packages.gzĀ andĀ Packages.xz, and the incremental versions), along with their MD5, SHA1, and SHA256 hashes, which ensures that the files havenā€™t been tampered with. TheseĀ PackagesĀ files contain a list of the Debian packages available on the mirror along with their hashes, which ensures in turn that the contents of the packages themselves havenā€™t been altered either.

The trusted keys are managed with theĀ apt-keyĀ command found in theĀ aptĀ package. This program maintains a keyring of GnuPG public keys, which are used to verify signatures in theĀ Release.gpgĀ files available on the mirrors. It can be used to add new keys manually (when non-official mirrors are needed). Generally however, only the official Kali keys are needed. These keys are automatically kept up-to-date by theĀ kali-archive-keyringĀ package (which puts the corresponding keyrings inĀ /etc/apt/trusted.gpg.d). However, the first installation of this particular package requires caution: even if the package is signed like any other, the signature cannot be verified externally. Cautious administrators should therefore check the fingerprints of imported keys before trusting them to install new packages:

# apt-key fingerprint
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
/etc/apt/trusted.gpg.d/debian-archive-buster-automatic.gpg
----------------------------------------------------------
pub   rsa4096 2019-04-14 [SC] [expires: 2027-04-12]
      80D1 5823 B7FD 1561 F9F7  BCDD DC30 D7C2 3CBB ABEE
uid           [ unknown] Debian Archive Automatic Signing Key (10/buster)
sub   rsa4096 2019-04-14 [S] [expires: 2027-04-12]

/etc/apt/trusted.gpg.d/debian-archive-buster-security-automatic.gpg
-------------------------------------------------------------------
pub   rsa4096 2019-04-14 [SC] [expires: 2027-04-12]
      5E61 B217 265D A980 7A23  C5FF 4DFA B270 CAA9 6DFA
uid           [ unknown] Debian Security Archive Automatic Signing Key (10/buster)
sub   rsa4096 2019-04-14 [S] [expires: 2027-04-12]

/etc/apt/trusted.gpg.d/debian-archive-buster-stable.gpg
-------------------------------------------------------
pub   rsa4096 2019-02-05 [SC] [expires: 2027-02-03]
      6D33 866E DD8F FA41 C014  3AED DCC9 EFBF 77E1 1517
uid           [ unknown] Debian Stable Release Key (10/buster)

/etc/apt/trusted.gpg.d/debian-archive-jessie-automatic.gpg
----------------------------------------------------------
pub   rsa4096 2014-11-21 [SC] [expires: 2022-11-19]
      126C 0D24 BD8A 2942 CC7D  F8AC 7638 D044 2B90 D010
uid           [ unknown] Debian Archive Automatic Signing Key (8/jessie)

/etc/apt/trusted.gpg.d/debian-archive-jessie-security-automatic.gpg
-------------------------------------------------------------------
pub   rsa4096 2014-11-21 [SC] [expires: 2022-11-19]
      D211 6914 1CEC D440 F2EB  8DDA 9D6D 8F6B C857 C906
uid           [ unknown] Debian Security Archive Automatic Signing Key (8/jessie)

/etc/apt/trusted.gpg.d/debian-archive-jessie-stable.gpg
-------------------------------------------------------
pub   rsa4096 2013-08-17 [SC] [expires: 2021-08-15]
      75DD C3C4 A499 F1A1 8CB5  F3C8 CBF8 D6FD 518E 17E1
uid           [ unknown] Jessie Stable Release Key

/etc/apt/trusted.gpg.d/debian-archive-stretch-automatic.gpg
-----------------------------------------------------------
pub   rsa4096 2017-05-22 [SC] [expires: 2025-05-20]
      E1CF 20DD FFE4 B89E 8026  58F1 E0B1 1894 F66A EC98
uid           [ unknown] Debian Archive Automatic Signing Key (9/stretch)
sub   rsa4096 2017-05-22 [S] [expires: 2025-05-20]

/etc/apt/trusted.gpg.d/debian-archive-stretch-security-automatic.gpg
--------------------------------------------------------------------
pub   rsa4096 2017-05-22 [SC] [expires: 2025-05-20]
      6ED6 F5CB 5FA6 FB2F 460A  E88E EDA0 D238 8AE2 2BA9
uid           [ unknown] Debian Security Archive Automatic Signing Key (9/stretch)
sub   rsa4096 2017-05-22 [S] [expires: 2025-05-20]

/etc/apt/trusted.gpg.d/debian-archive-stretch-stable.gpg
--------------------------------------------------------
pub   rsa4096 2017-05-20 [SC] [expires: 2025-05-18]
      067E 3C45 6BAE 240A CEE8  8F6F EF0F 382A 1A7B 6500
uid           [ unknown] Debian Stable Release Key (9/stretch)

/etc/apt/trusted.gpg.d/kali-archive-keyring.gpg
-----------------------------------------------
pub   rsa4096 2012-03-05 [SC] [expires: 2023-01-16]
      44C6 513A 8E4F B3D3 0875  F758 ED44 4FF0 7D8D 0BF6
uid           [ unknown] Kali Linux Repository
sub   rsa4096 2012-03-05 [E] [expires: 2023-01-16]

When a third-party package source is added to theĀ sources.listĀ file, APT needs to be told to trust the corresponding GPG authentication key (otherwise it will keep complaining that it canā€™t ensure the authenticity of the packages coming from that repository). The first step is of course to get the public key. More often than not, the key will be provided as a small text file, which we will callĀ key.ascĀ in the following examples.

To add the key to the trusted keyring, the administrator can runĀ apt-key add < key.asc. Another way is to use theĀ synapticĀ graphical interface: its Authentication tab in theĀ Settings ā†’ RepositoriesĀ menu provides the ability to import a key from theĀ key.ascĀ file.

For people who prefer a dedicated application and more details on the trusted keys, it is possible to useĀ gui-apt-keyĀ (in the package of the same name), a small graphical user interface that manages the trusted keyring.

Once the appropriate keys are in the keyring, APT will check the signatures before any risky operation, so that front-ends will display a warning if asked to install a package whose authenticity canā€™t be ascertained.

9.4. APT Package Reference: Digging Deeper into the Debian Package System

Now it is time to dive really deep into Debian and Kaliā€™s package system. At this point, we are going to move beyond tools and syntax and focus more on the nuts and bolts of the packaging system. This behind-the-scenes view will help you understand how APT works at its foundation and will give you insight into how to seriously streamline and customize your Kali system. You may not necessarily memorize all the material in this section, but the walk-through and reference material will serve you well as you grow in your mastery of the Kali Linux system.

So far, you have interacted with APTā€™s package data through the various tools designed to interface with it. Next, we will dig deeper and take a look inside the packages and look at the internalĀ meta-informationĀ (or information about other information) used by the package management tools.

This combination of a file archive and of meta-information is directly visible in the structure of aĀ .debĀ file, which is simply anĀ arĀ archive, concatenating three files:

$ ar t /var/cache/apt/archives/apt_1.4~beta1_amd64.deb
debian-binary
control.tar.gz
data.tar.xz

TheĀ debian-binaryĀ file contains a single version number describing the format of the archive:

$ ar p /var/cache/apt/archives/apt_1.4~beta1_amd64.deb debian-binary
2.0

TheĀ control.tar.gzĀ archive contains meta-information:

$ ar p /var/cache/apt/archives/apt_1.4~beta1_amd64.deb control.tar.gz | tar -tzf -
./
./conffiles
./control
./md5sums
./postinst
./postrm
./preinst
./prerm
./shlibs
./triggers

And finally, theĀ data.tar.xzĀ archive (the compression format might vary) contains the actual files to be installed on the file system:

$ ar p /var/cache/apt/archives/apt_1.4~beta1_amd64.deb data.tar.xz | tar -tJf -
./
./etc/
./etc/apt/
./etc/apt/apt.conf.d/
./etc/apt/apt.conf.d/01autoremove
./etc/apt/preferences.d/
./etc/apt/sources.list.d/
./etc/apt/trusted.gpg.d/
./etc/cron.daily/
./etc/cron.daily/apt-compat
./etc/kernel/
./etc/kernel/postinst.d/
./etc/kernel/postinst.d/apt-auto-removal
./etc/logrotate.d/
./etc/logrotate.d/apt
./lib/
./lib/systemd/
[...]

Note that in this example, you are viewing aĀ .debĀ package in APTā€™s archive cache and that your archive may contain files with different version numbers than what is shown.

In this section, we will introduce this meta-information contained in each package and show you how to leverage it.

9.4.1. The control File

We will begin by looking at theĀ controlĀ file, which is contained in theĀ control.tar.gzĀ archive. TheĀ controlĀ file contains the most vital information about the package. It uses a structure similar to email headers and can be viewed with theĀ dpkg -IĀ command. For example, theĀ controlĀ file forĀ aptĀ looks like this:

$ dpkg -I apt_1.4~beta1_amd64.deb control
Package: apt
Version: 1.4~beta1
Architecture: amd64
Maintainer: APT Development Team
Installed-Size: 3478
Depends: adduser, gpgv | gpgv2 | gpgv1, debian-archive-keyring, init-system-helpers (>= 1.18~), libapt-pkg5.0 (>= 1.3~rc2), libc6 (>= 2.15), libgcc1 (>= 1:3.0), libstdc++6 (>= 5.2)
Recommends: gnupg | gnupg2 | gnupg1
Suggests: apt-doc, aptitude | synaptic | wajig, dpkg-dev (>= 1.17.2), powermgmt-base, python-apt
Breaks: apt-utils (<< 1.3~exp2~)
Replaces: apt-utils (<< 1.3~exp2~)
Section: admin
Priority: important
Description: commandline package manager
 This package provides commandline tools for searching and
 managing as well as querying information about packages
 as a low-level access to all features of the libapt-pkg library.
 .
 These include:
  * apt-get for retrieval of packages and information about them
    from authenticated sources and for installation, upgrade and
    removal of packages together with their dependencies
  * apt-cache for querying available information about installed
    as well as installable packages
  * apt-cdrom to use removable media as a source for packages
  * apt-config as an interface to the configuration settings
  * apt-key as an interface to manage authentication keys

In this section, we will walk you through the control file and explain the various fields. Each of these will give you a better understanding of the packaging system, give you more fine-tuned configuration control, and provide you with insight needed to troubleshoot problems that may occur.

Dependencies: the Depends Field

The package dependencies are defined in theĀ DependsĀ field in the package header. This is a list of conditions to be met for the package to work correctlyā€”this information is used by tools such asĀ aptĀ in order to install the required libraries, in appropriate versions fulfilling the dependencies of the package to be installed. For each dependency, you can restrict the range of versions that meet that condition. In other words, it is possible to express the fact that you need the package libc6 in a version equal to or greater than ā€œ2.15ā€ (written ā€œlibc6 (>= 2.15)ā€). Version comparison operators are as follows:

  • <<Ā - less than.
  • <=Ā - less than or equal to.
  • =Ā - equal to (note that ā€œ2.6.1ā€ is not equal to ā€œ2.6.1-1ā€).
  • >=Ā - greater than or equal to.
  • >>Ā - greater than.

In a list of conditions to be met, the comma serves as a separator, interpreted as a logical ā€œAND.ā€ In conditions, the vertical bar (ā€|ā€) expresses a logical ā€œORā€ (it is an inclusive ā€œOR,ā€ not an exclusive ā€œeither/orā€). Carrying greater priority than ā€œAND,ā€ you can use it as many times as necessary. Thus, the dependency ā€œ(A OR B) AND Cā€ is writtenĀ A | B, C. In contrast, the expression ā€œA OR (B AND C)ā€ should be written as ā€œ(A OR B) AND (A OR C)ā€, since theĀ DependsĀ field does not tolerate parentheses that change the order of priorities between the logical operators ā€œORā€ and ā€œANDā€. It would thus be writtenĀ A | B, A | C. SeeĀ https://www.debian.org/doc/debian-policy/ch-relationships.htmlĀ for more information.

The dependencies system is a good mechanism for guaranteeing the operation of a program but it has another use with metapackages. These are empty packages that only describe dependencies. They facilitate the installation of a consistent group of programs preselected by the metapackage maintainer; as such,Ā apt install metapackageĀ will automatically install all of these programs using the metapackageā€™s dependencies. TheĀ gnome,Ā kali-tools-wireless, andĀ kali-linux-largeĀ packages are examples of metapackages. For more information on Kaliā€™s metapackages, seeĀ https://tools.kali.org/kali-metapackages

Pre-Depends, a More Demanding Depend

Pre-dependencies, which are listed in theĀ Pre-DependsĀ field in the package headers, complete the normal dependencies; their syntax is identical. A normal dependency indicates that the package in question must be unpacked and configured before configuration of the package declaring the dependency. A pre-dependency stipulates that the package in question must be unpacked and configured before execution of the pre-installation script of the package declaring the pre-dependency, that is before its installation.

A pre-dependency is very demanding forĀ aptĀ because it adds a strict constraint on the ordering of the packages to install. As such, pre-dependencies are discouraged unless absolutely necessary. It is even recommended to consult other developers onĀ debian-devel@lists.debian.orgĀ before adding a pre-dependency as it is generally possible to find another solution as a work-around.

Recommends, Suggests, and Enhances Fields

TheĀ RecommendsĀ andĀ SuggestsĀ fields describe dependencies that are not compulsory. The recommended dependencies, the most important, considerably improve the functionality offered by the package but are not indispensable to its operation. The suggested dependencies, of secondary importance, indicate that certain packages may complement and increase their respective utility, but it is perfectly reasonable to install one without the others.

You should always install the recommended packages unless you know exactly why you do not need them. Conversely, it is not necessary to install suggested packages unless you know why you need them.

TheĀ EnhancesĀ field also describes a suggestion, but in a different context. It is indeed located in the suggested package, and not in the package that benefits from the suggestion. Its interest lies in that it is possible to add a suggestion without having to modify the package that is concerned. Thus, all add-ons, plug-ins, and other extensions of a program can then appear in the list of suggestions related to the software. Although it has existed for several years, this last field is still largely ignored by programs such asĀ aptĀ orĀ synaptic. The original goal was to let a package likeĀ xul-ext-adblock-plusĀ (a Firefox extension) declareĀ Enhances: firefox, firefox-esrĀ and thus appear in the list of suggested packages associated toĀ firefoxĀ andĀ firefox-esr.

Conflicts: the Conflicts Field

TheĀ ConflictsĀ field indicates when a package cannot be installed simultaneously with another. The most common reasons for this are that both packages include a file of the same name, provide the same service on the same transmission control protocol (TCP) port, or would hinder each otherā€™s operation.

If it triggers a conflict with an already installed package,Ā dpkgĀ will refuse to install a package, except if the new package specifies that it will replace the installed package, in which caseĀ dpkgĀ will choose to replace the old package with the new one. APT always follows your instructions: if you choose to install a new package, it will automatically offer to uninstall the package that poses a problem.

Incompatibilities: the Breaks Field

TheĀ BreaksĀ field has an effect similar to that of theĀ ConflictsĀ field, but with a special meaning. It signals that the installation of a package will break another package (or particular versions of it). In general, this incompatibility between two packages is transitory and theĀ BreaksĀ relationship specifically refers to the incompatible versions.

When a package breaks an already installed package,Ā dpkgĀ will refuse to install it, andĀ aptĀ will try to resolve the problem by updating the package that would be broken to a newer version (which is assumed to be fixed and, thus, compatible again).

This type of situation may occur in the case of updates without backwards compatibility: this is the case if the new version no longer functions with the older version and causes a malfunction in another program without making special provisions. TheĀ BreaksĀ field helps prevent these types of problems.

Provided Items: the Provides Field

This field introduces the very interesting concept of aĀ virtual package. It has many roles, but two are of particular importance. The first role consists in using a virtual package to associate a generic service with it (the package provides the service). The second indicates that a package completely replaces another and that for this purpose, it can also satisfy the dependencies that the other would satisfy. It is thus possible to create a substitution package without having to use the same package name.

Metapackage and Virtual Package

It is essential to clearly distinguish metapackages from virtual packages. The former are real packages (including realĀ .debĀ files), whose only purpose is to express dependencies.

Virtual packages, however, do not exist physically; they are only a means of identifying real packages based on common, logical criteria (for example, service provided, or compatibility with a standard program or a pre-existing package).

Providing a Service

Letā€™s discuss the first case in greater detail with an example: all mail servers, such asĀ postfixĀ orĀ sendmailĀ are said to provide theĀ mail-transport-agentĀ virtual package. Thus, any package that needs this service to be functional (e.g. a mailing list manager, such as smartlist or sympa) simply states in its dependencies that it requires aĀ mail-transport-agentĀ instead of specifying a large yet incomplete list of possible solutions. Furthermore, it is useless to install two mail servers on the same machine, which is why each of these packages declares a conflict with theĀ mail-transport-agentĀ virtual package. A conflict between a package and itself is ignored by the system, but this technique will prohibit the installation of two mail servers side by side.

Interchangeability with Another Package

TheĀ ProvidesĀ field is also interesting when the content of a package is included in a larger package. For example, theĀ libdigest-md5-perlĀ Perl module was an optional module in Perl 5.6, and has been integrated as standard in Perl 5.8. As such, the packageĀ perlĀ has since version 5.8 declaredĀ Provides: libdigest-md5-perlĀ so that the dependencies on this package are met if the system has Perl 5.8 (or newer). TheĀ libdigest-md5-perlĀ package itself was deleted, since it no longer had any purpose when old Perl versions were removed.

Figure 3: Use of a Provides Field in Order to Not Break Dependencies

Figure 3: Use of a Provides Field in Order to Not Break Dependencies

This feature is very useful, since it is never possible to anticipate the vagaries of development and it is necessary to be able to adjust to renaming, and other automatic replacement, of obsolete software.

Replacing Files: The Replaces Field

TheĀ ReplacesĀ field indicates that the package contains files that are also present in another package, but that the package is legitimately entitled to replace them. Without this specification,Ā dpkgĀ fails, stating that it cannot overwrite the files of another package (technically, it is possible to force it to do so with theĀ --force-overwriteĀ option, but that is not considered standard operation). This allows identification of potential problems and requires the maintainer to study the matter prior to choosing whether to add such a field.

The use of this field is justified when package names change or when a package is included in another. This also happens when the maintainer decides to distribute files differently among various binary packages produced from the same source package: a replaced file no longer belongs to the old package, but only to the new one.

If all of the files in an installed package have been replaced, the package is considered to be removed. Finally, this field also encouragesĀ dpkgĀ to remove the replaced package where there is a conflict.

9.4.2. Configuration Scripts

In addition to theĀ controlĀ file, theĀ control.tar.gzĀ archive for each Debian package may contain a number of scripts (postinst,Ā postrm,Ā preinst,Ā prerm) called byĀ dpkgĀ at different stages in the processing of a package. We can useĀ dpkg -IĀ to show these files as they reside in aĀ .debĀ package archive:

$ dpkg -I /var/cache/apt/archives/zsh_5.3-1_amd64.deb | head
 new debian package, version 2.0.
 size 814486 bytes: control archive=2557 bytes.
     838 bytes,    20 lines      control
    3327 bytes,    43 lines      md5sums
     969 bytes,    41 lines   *  postinst             #!/bin/sh
     348 bytes,    20 lines   *  postrm               #!/bin/sh
     175 bytes,     5 lines   *  preinst              #!/bin/sh
     175 bytes,     5 lines   *  prerm                #!/bin/sh
 Package: zsh
 Version: 5.3-1
$ dpkg -I zsh_5.3-1_amd64.deb preinst
#!/bin/sh
set -e
# Automatically added by dh_installdeb
dpkg-maintscript-helper symlink_to_dir /usr/share/doc/zsh zsh-common 5.0.7-3 -- "$@"
# End automatically added section

TheĀ Debian PolicyĀ describes each of these files in detail, specifying the scripts called and the arguments they receive. These sequences may be complicated, since if one of the scripts fails,Ā dpkgĀ will try to return to a satisfactory state by canceling the installation or removal in progress (insofar as it is possible).

TheĀ pkgĀ Database

You can traverse theĀ dpkgĀ database on the filesystem atĀ /var/lib/dpkg/. This directory contains a running record of all the packages that have been installed on the system. All of the configuration scripts for installed packages are stored in theĀ /var/lib/dpkg/info/Ā directory, in the form of a file prefixed with the packageā€™s name:

$ ls /var/lib/dpkg/info/zsh.*
/var/lib/dpkg/info/zsh.list
/var/lib/dpkg/info/zsh.md5sums
/var/lib/dpkg/info/zsh.postinst
/var/lib/dpkg/info/zsh.postrm
/var/lib/dpkg/info/zsh.preinst
/var/lib/dpkg/info/zsh.prerm

This directory also includes a file with theĀ .listĀ extension for each package, containing the list of files that belong to that package:

$ head /var/lib/dpkg/info/zsh.list
/.
/bin
/bin/zsh
/bin/zsh5
/usr
/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/zsh
/usr/lib/x86_64-linux-gnu/zsh/5.2
/usr/lib/x86_64-linux-gnu/zsh/5.2/zsh
[...]

TheĀ /var/lib/dpkg/statusĀ file contains a series of data blocks (in the format of the famous mail headers request for comment, RFC 2822) describing the status of each package. The information from theĀ controlĀ file of the installed packages is also replicated there.

$ more /var/lib/dpkg/status
Package: gnome-characters
Status: install ok installed
Priority: optional
Section: gnome
Installed-Size: 1785
Maintainer: Debian GNOME Maintainers
Architecture: amd64
Version: 3.20.1-1
[...]

Letā€™s discuss the configuration files and see how they interact. In general, theĀ preinstĀ script is executed prior to installation of the package, while theĀ postinstĀ follows it. Likewise,Ā prermĀ is invoked before removal of a package andĀ postrmĀ afterwards. An update of a package is equivalent to removal of the previous version and installation of the new one. It is not possible to describe in detail all the possible scenarios here but we will discuss the most common two: an installation/update and a removal.

These sequences can be quite confusing, but a visual representation may help.Ā Manoj Srivastava made some diagramsĀ explaining how the configuration scripts are called byĀ dpkg.Ā Similar diagrams have also been developed by the Debian Women projectĀ ; they are a bit simpler to understand, but less complete.

Caution: Symbolic Names of the Scripts

The sequences described in this section call configuration scripts by specific names, such asĀ old-prermĀ orĀ new-postinst. They are, respectively, theĀ prermĀ script contained in the old version of the package (installed before the update) and theĀ postinstĀ script contained in the new version (installed by the update).

Installation and Upgrade Script Sequence

Here is what happens during an installation (or an update):

  1. For an update,Ā dpkgĀ calls theĀ old-prerm upgrade new-version.
  2. Still for an update,Ā dpkgĀ then executesĀ new-preinst upgrade old-version; for a first installation, it executesĀ new-preinst install. It may add the old version in the last parameter if the package has already been installed and removed (but not purged, the configuration files having been retained).
  3. The new package files are then unpacked. If a file already exists, it is replaced, but a backup copy is made and temporarily stored.
  4. For an update,Ā dpkgĀ executesĀ old-postrm upgrade new-version.
  5. dpkgĀ updates all of the internal data (file list, configuration scripts, etc.) and removes the backups of the replaced files. This is the point of no return:Ā dpkgĀ no longer has access to all of the elements necessary to return to the previous state.
  6. dpkgĀ will update the configuration files, prompting you to decide if it is unable to automatically manage this task. The details of this procedure are discussed inĀ Checksums, Conffiles.
  7. Finally,Ā dpkgĀ configures the package by executingĀ new-postinst configure last-version-configured.

Package Removal

Here is what happens during a package removal.

  1. dpkgĀ callsĀ prerm remove.
  2. dpkgĀ removes all of the packageā€™s files, with the exception of the configuration files and configuration scripts.
  3. dpkgĀ executesĀ postrm remove. All of the configuration scripts, exceptĀ postrm, are removed. If you have not used the purge option, the process stops here.
  4. For a complete purge of the package (command issued withĀ dpkg --purgeĀ orĀ dpkg -P), the configuration files are also deleted, as well as a certain number of copies (*.dpkg-tmp,Ā *.dpkg-old,Ā *.dpkg-new) and temporary files;Ā dpkgĀ then executesĀ postrm purge.

In some cases, a package might useĀ debconfĀ to require configuration information from you: the four scripts detailed above are then complemented by aĀ configĀ script designed to acquire that information. During installation, this script defines in detail what questionsĀ debconfĀ will ask. The responses are recorded in theĀ debconfĀ database for future reference. The script is generally executed byĀ aptĀ prior to installing packages one by one in order to group all the questions together at the beginning of the process. The pre- and post-installation scripts can then use this information to operate according to your wishes.

TheĀ debconfĀ Tool

TheĀ debconfĀ tool was created to resolve a recurring problem in Debian. All Debian packages unable to function without a minimum of configuration used to ask questions with calls to theĀ echoĀ andĀ readĀ commands inĀ postinstĀ shell scripts (and other similar scripts). This forced the installer to babysit large installations or updates in order to respond to various configuration queries as they arose. These manual interactions have now been almost entirely dispensed with, thanks toĀ debconf.

TheĀ debconfĀ tool has many interesting features: It requires the developer to specify user interaction; it allows localization of all the displayed strings (all translations are stored in theĀ templatesĀ file describing the interactions); it provides different frontends for questions (text mode, graphical mode, non-interactive); and it allows creation of a central database of responses to share the same configuration with several computers. The most important feature is that all of the questions can be presented in a row, all at once, prior to starting a long installation or update process. Now, you can go about your business while the system handles the installation on its own, without having to stay there staring at the screen, waiting for questions to pop up.

9.4.3. Checksums, Conffiles

In addition to the maintainer scripts and control data already mentioned in the previous sections, theĀ control.tar.gzĀ archive of a Debian package may contain other interesting files:

# ar p /var/cache/apt/archives/bash_4.4-2_amd64.deb control.tar.gz | tar -tzf -
./
./conffiles
./control
./md5sums
./postinst
./postrm
./preinst
./prerm

The firstā€”md5sumsā€”contains the MD5 checksums for all of the packageā€™s files. Its main advantage is that it allowsĀ dpkg --verifyĀ to check if these files have been modified since their installation. Note that when this file doesnā€™t exist,Ā dpkgĀ will generate it dynamically at installation time (and store it in the dpkg database just like other control files).

conffilesĀ lists package files that must be handled as configuration files. Configuration files can be modified by the administrator, andĀ dpkgĀ will try to preserve those changes during a package update.

In effect, in this situation,Ā dpkgĀ behaves as intelligently as possible: if the standard configuration file has not changed between the two versions, it does nothing. If, however, the file has changed, it will try to update this file. Two cases are possible: either the administrator has not touched this configuration file, in which caseĀ dpkgĀ automatically installs the new version; or the file has been modified, in which caseĀ dpkgĀ asks the administrator which version they wish to use (the old one with modifications, or the new one provided with the package). To assist in making this decision,Ā dpkgĀ offers to display aĀ diffĀ that shows the difference between the two versions. If you choose to retain the old version, the new one will be stored in the same location in a file with theĀ .dpkg-distĀ suffix. If you choose the new version, the old one is retained in a file with theĀ .dpkg-oldĀ suffix. Another available action consists of momentarily interruptingĀ dpkgĀ to edit the file and attempt to reinstate the relevant modifications (previously identified withĀ diff).

dpkgĀ handles configuration file updates, but, while doing so, regularly interrupts its work to ask for input from the administrator. This can be time consuming and inconvenient. Fortunately, you can instructĀ dpkgĀ to respond to these prompts automatically. TheĀ --force-confoldĀ option retains the old version of the file, whileĀ --force-confnewĀ will use the new version. These choices are respected, even if the file has not been changed by the administrator, which only rarely has the desired effect. Adding theĀ --force-confdefĀ option tellsĀ dpkgĀ to decide by itself when possible (in other words, when the original configuration file has not been touched), and only usesĀ --force-confnewĀ orĀ --force-confoldĀ for other cases.

These options apply toĀ dpkg, but most of the time the administrator will work directly with theĀ aptitudeĀ orĀ aptĀ programs. It is, thus, necessary to know the syntax used to indicate the options to pass to theĀ dpkgĀ command (their command line interfaces are very similar).

# apt -o DPkg::options::="--force-confdef" -o DPkg::options::="--force-confold" full-upgrade

These options can be stored directly inĀ aptā€™s configuration. To do so, simply write the following line in theĀ /etc/apt/apt.conf.d/localĀ file:

DPkg::options { "--force-confdef"; "--force-confold"; }

Including this option in the configuration file means that it will also be used in a graphical interface such asĀ aptitude.

Conversely, you can also forceĀ dpkgĀ to ask configuration file questions. TheĀ --force-confaskĀ option instructsĀ dpkgĀ to display the questions about the configuration files, even in cases where they would not normally be necessary. Thus, when reinstalling a package with this option,Ā dpkgĀ will ask the questions again for all of the configuration files modified by the administrator. This is very convenient, especially for reinstalling the original configuration file if it has been deleted and no other copy is available: a normal re-installation wonā€™t work, becauseĀ dpkgĀ considers removal as a form of legitimate modification, and, thus, doesnā€™t install the desired configuration file.

9.5. Summary

In this section, we learned more about the Debian package system, discussed the Advanced Package Tool (APT) andĀ dpkg, learned about basic package interaction, advanced APT configuration and usage, and dug deeper into the Debian package system with a brief reference of theĀ .debĀ file format. We looked at theĀ controlĀ file, configuration scripts, checksums, and theĀ conffilesĀ file.

Summary Tips:

A Debian package is a compressed archive of a software application. It contains the applicationā€™s files as well as other metadata including the names of the dependencies that the application needs plus any scripts that enable the execution of commands at different stages in the packageā€™s lifecycle (installation, removal, upgrades).

TheĀ dpkgĀ tool, contrary toĀ aptĀ andĀ apt-getĀ (of the APT family), has no knowledge of all the available packages that could be used to fulfill package dependencies. Thus, to manage Debian packages, you will likely use the latter tools as they are able to automatically resolve dependency issues.

You can use APT to install and remove applications, update packages, and even upgrade your entire system. Here are the key points that you should know about APT and its configuration:

  • TheĀ sources.listĀ file is the key configuration file for defining package sources (or repositories that contain packages).
  • Debian and Kali use three sections to differentiate packages according to the licenses chosen by the authors of each work:Ā mainĀ contains all packages that fully comply with theĀ Debian Free Software Guidelines;Ā non-freeĀ contains software that does not (entirely) conform to the Free Software Guidelines but can nevertheless be distributed without restrictions; andĀ contribĀ (contributions) includes open source software that cannot function without some non-free elements.
  • Kali maintains several repositories including:Ā kali-rolling, which is the main repository for end-users and should always contain installable and recent packages; andĀ kali-dev, which is used by Kali developers and is not for public use.
  • When working with APT, you should first download the list of currently-available packages withĀ apt update.
  • You can add a package to the system with a simpleĀ apt install package. APT will automatically install the necessary dependencies.
  • To remove a package useĀ apt remove package. It will also remove the reverse dependencies of the package (i.e. packages that depend on the package to be removed).
  • To remove all data associated with a package, you can ā€œpurgeā€ the package with theĀ apt purge packageĀ command. Unlike a removal, this will not only remove the package but also its configuration files and sometimes the associated user data.

We recommend regular upgrades to install the latest security updates. To upgrade, useĀ apt updateĀ followed by eitherĀ apt upgrade,Ā apt-get upgrade, orĀ aptitude safe-upgrade. These commands look for installed packages that can be upgraded without removing any packages.

For more important upgrades, such as major version upgrades, useĀ apt full-upgrade. With this instruction,Ā aptĀ will complete the upgrade even if it has to remove some obsolete packages or install new dependencies. This is also the command that you should use for regular upgrades of your Kali Rolling system. Review the pros and cons of updates we outlined in this chapter.

Several tools can be used to inspect Debian packages:

  • dpkg --listfiles packageĀ (orĀ -L) - lists the files that were installed by the specified package.
  • dpkg --search fileĀ (orĀ -S) - finds any packages containing the file or path passed in the argument.
  • dpkg --listĀ (orĀ -l) - displays the list of packages known to the system and their installation status.
  • dpkg --contents file.debĀ (orĀ -c) - lists all the files in a particularĀ .debĀ file.
  • dpkg --info file.debĀ (orĀ -I) - displays the headers of the specifiedĀ .debĀ file.
  • The variousĀ apt-cacheĀ subcommands display much of the information stored in APTā€™s internal database.

To avoid excessive disk usage, you should regularly sort throughĀ /var/cache/apt/archives/. Two commands can be used for this:Ā apt cleanĀ (orĀ apt-get clean) entirely empties the directory;Ā apt autocleanĀ (apt-get autoclean) only removes packages that can no longer be downloaded because they have disappeared from the mirror and are therefore useless.

aptitudeĀ is an interactive program that can be used in semi-graphical mode on the console. It is an extremely robust program that can help you install and troubleshoot packages.

synapticĀ is a graphical package manager that features a clean and efficient graphical interface.

As an advanced user, you can create files inĀ /etc/apt/apt.conf.d/Ā to configure certain aspects of APT. You can also manage package priorities, track automatically installed packages, work with several distributions or architectures at once, use cryptographic signatures to validate packages, and upgrade files using the techniques outlined in this chapter.

In spite of the Debian or Kali maintainersā€™ best efforts, a system upgrade isnā€™t always as smooth as we would hope. When this happens, you can look at theĀ Kali bug trackerĀ and at theĀ Debian bug tracking systemĀ atĀ https://bugs.debian.org/packageĀ to check whether the problem has already been reported. You can also try to downgrade the package or to debug and repair a failed package maintainer script.

9.6.1. Mirror redirection

Exercise:

  1. Find out which mirror would serve your ISO download request, if you were to try to download a Kali ISO fromĀ cdimage.kali.org.
  2. Configure a source entry in your sources.list file. Update your package cache.
  3. Add the kali-bleeding-edge repository to your system and install the bleeding-edge version of theĀ setĀ package

Exercise solution:

  1. Check the mirror with:
kali@kali:~$ curl -sI https://cdimage.kali.org/README
kali@kali:~$
  1. Ensure source repositories are enabled through this line in /etc/apt/sources.list:
deb-src https://http.kali.org/kali kali-rolling main contrib non-free

If it is commented out, uncomment the line.

  1. To enable the kali-bleeding edge repos, add this line to /etc/apt/sources.list:
deb https://http.kali.org/kali kali-bleeding-edge contrib non-free main

Next, sync with apt-get update:

kali@kali:~$ sudo apt-get update
kali@kali:~$

Then install the bleeding edge version of set:

kali@kali:~$ sudo apt install set/kali-bleeding-edge
kali@kali:~$

9.6.2. Getting to know dpkg

Exercise:

  1. Find the path to theĀ atk6-alive6Ā binary.
  2. Determine the package that installed it and the other files included in the package.
  3. Search for locally installed packages which have ā€œwifiā€ in their name.
  4. Search for tools in the Kali repository which have ā€œwifiā€ in their name.
  5. List the installed files which originated from theĀ nmapĀ package.

Exercise solution:

  1. Find the path:
kali@kali:~$ which atk6-alive6
kali@kali:~$
  1. Determine what installed atk-alive6 and other files include in the package:
kali@kali:~$ sudo dpkg -S atk6-alive6
kali@kali:~$
  1. Search for locally install packages with ā€œwifiā€ in the name:
kali@kali:~$ dpkg -l | grep wifi
kali@kali:~$
  1. Search for tools in the Kali repository which have ā€œwifiā€ in their name:
kali@kali:~$ sudo apt-cache search wifi | grep wifi
kali@kali:~$
  1. List the files that originated from the nmap package:
kali@kali:~$ sudo dpkg -L nmap
kali@kali:~$

9.6.3. Playing with dpkg-deb

Exercise:

In this exercise, we want to install Nessus. Nessus is not a simple apt-get installation. It is a process:

  1. Downloading the .deb file from Nessus
  2. Install .deb with dpkg
  3. Register Nessus and get an activation code by email
  4. Generate a challenge code with nessuscli in Kali
  5. Submit the challenge and activation to get access to plugins
  6. Download plugins and install them

This is a long process and isnā€™t simple. Using the skills we demonstrated in this chapter, download and install Nessus and create a package that includes the plugins and installs them, automatically.

  1. Find, download, install and register the Free Nessus Debian package.
  2. Instead of programmatically installing the plugins through the Nessus web interface, save the plugins to a local file.
  3. Slipstream the signatures into the NessusĀ .debĀ package so that you will be able to install Nessus (say across multiple computers), without having each computer re-download the signatures.
  4. Create a new NessusĀ .debĀ package that automatically installs the plugins.

Exercise solution:

First, youā€™ll have to install Nessus the ā€œstandardā€ way. There are lots of steps.Ā This video solutionĀ shows the process in more detail.

The details for the packages are onĀ this pageĀ andĀ this page.

Next, with Nessus properly installed, we can modify the package.

  1. Extract the package. Are you copy and pasting?Ā Note that your version numbers may differ.
kali@kali:~/Downloads$ sudo dpkg-deb -R Nessus-6.9.0-debian6_amd64.deb nessus #Raw extract the package
  1. List the contents of the package:
kali@kali:~$ ls -lR ./nessus
kali@kali:~$
  1. Copy the plugins file toĀ nessus/opt/nessus/var/nessus:
kali@kali:~$ cp ~/Downloads/all-2.0.tar.gz nessus/opt/nessus/var/nessus
kali@kali:~$

Edit the Debian postinst file, find this section, make changes as appropriate:

kali@kali:~$ nano nessus/DEBIAN/postinst
kali@kali:~$
  1. Edit the postinst file to import the offline signatures. Add somewhere inĀ postinst:
echo "UBERHAX - Updating plugins from local file..."
rm -f ${NESSUS_PREFIX}/lib/nessus/plugins/MD5
${NESSUS_PREFIX}/sbin/nessuscli update ${NESSUS_PREFIX}/var/nessus/all-2.0.tar.gz
${NESSUS_PREFIX}/sbin/nessusd -R

test -f ${NESSUS_PREFIX}/etc/nessus/nessus-fetch.rc && {
        echo "Fetching the newest plugins from nessus.org..."
        rm -f ${NESSUS_PREFIX}/lib/nessus/plugins/MD5
        ${NESSUS_PREFIX}/sbin/nessuscli update --plugins-only
        ${NESSUS_PREFIX}/sbin/nessusd -R
}

Letā€™s clean up after ourselves by deleting the signature file to save space. We will do this in theĀ postrmĀ file:

kali@kali:~$ rm -f ${NESSUS_PREFIX}/var/nessus/all-2.0.tar.gz
kali@kali:~$

Repackage the deb file. Your version may vary:

kali@kali:~$ dpkg-deb -b nessus nessus_6.9.0_amd64.deb
kali@kali:~$

9.6.4. Kali multiarch

This will be a fun exercise because it is fairly simple, uses some of the package commands youā€™ve learned and allows you to run Windows programs from within Kali, thanks to Wine. However, it may sound a lot more complicated than it is because you will have to install a foreign architecture (i386).

Exercise:

  1. Add the 32-bit architecture option to your Kali instance using dpkg.
  2. Install wine32
  3. Run the WindowsĀ ipscanĀ program using Wine.

Exercise solution:

The solution is fairly straight-forward. However, do not miss the i386 command. This is the turning point of the exercise, where we operate in a shell that imitates the i386 environment.

kali@kali:~$ sudo apt install wine
kali@kali:~$
kali@kali:~$ wine
it looks like wine32 is missing, you should install it.
multiarch needs to be enabled first.  With sudo, please
execute "dpkg --add-architecture i386 && apt-get update &&
apt-get install wine32"
Usage: wine PROGRAM [ARGUMENTS...]   Run the specified program
       wine --help                   Display this help and exit
       wine --version                Output version information and exit
kali@kali:~$
kali@kali:~$ sudo dpkg --print-architecture
kali@kali:~$
kali@kali:~$ sudo dpkg --add-architecture i386
kali@kali:~$
kali@kali:~$ sudo dpkg --print-foreign-architectures
kali@kali:~$
kali@kali:~$ i386 # change architecture in new program environment
$
$ sudo apt update
$
$ sudo apt install wine32
$
$ wget https://sourceforge.net/projects/ipscan/files/ipscan2-binary/2.21/ipscan221.exe/download -O ipscan221.exe
$
$ wine ipscan221.exe

Figure 4: wine

Figure 4: wine


Questions

Run the following command:

apt-cache search nmap

Why is the tool ā€œatacā€ in the results?


Answers:

This is due to the long description of the package.

Next Module ā†’