Basic Package Interaction

Topic Progress:

8.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.

8.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.

8.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 kali-rolling/main amd64 oclgausscrack amd64 1.3-1kali3 [30.7 kB]
Get:2 kali-rolling/main amd64 truecrack amd64 3.6+git20150326-0kali1 [2,558 kB]
Get:3 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

8.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 aptitudeapt-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.

8.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 dpkgand 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 Section, “RecommendsSuggests, 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.

8.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

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

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*'
| 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
 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 $?
$ dpkg --compare-versions 1.2-3 lt 1.1-4
$ echo $?
$ dpkg --compare-versions 2.6.0pre3-1 lt 2.6.0-1
$ echo $?

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.


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 aptdrops 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 meta-packages, 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 .desktopfiles from all Debian packages). It knows about tags and returns results in a matter of milliseconds.

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.

8.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 , and check whether the problem has already been reported. If it hasn't, you should report it yourself (see Section 6.3, "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 Section 9.1, "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 Section, "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 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-getcommands. 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-rolling 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).

8.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 8.1, "The aptitude package manager", 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.

The aptitude package manager
Figure 8.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

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 Section 8.3.4, "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 dpkgaptitude 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 8.2, “synaptic Package Manager”) 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.

synaptic Package Manager
Figure 8.2. synaptic Package Manager