# 10. Advanced Usage

Kali Linux is a highly customizable penetration testing platform, allowing modifications at multiple levels.

**1. Source Code Customization**

* All package sources are publicly available for retrieval, modification, and rebuilding.
* Special attention is given to **Linux Kernel customization**, which involves retrieving sources, configuring the build, and compiling the kernel.

**2. Custom Live ISO**

* The **live-build** tool allows customization of ISO images, including replacing default packages with custom Debian packages.

**3. Persistent Live USB**

* A **persistent USB** setup retains files and system changes across reboots, making it portable and flexible.

These customization options make Kali a powerful tool for security professionals.

## 10.1. Modifying Kali Packages

Modifying Kali packages is typically done by contributors and developers to update versions, tweak configurations, or fix bugs. However, there are cases where users might need to modify a package to meet specific needs. Understanding how to do this can be highly valuable.

**Why Modify a Package Instead of Running from Source?**

* Running a modified version directly from the source (via Git) works in some cases, especially when changes are confined to the user's home directory.
* However, system-wide installations using `make install` can clutter the filesystem with unmanaged files, leading to dependency issues.
* Properly packaging modifications allows for easier sharing, deployment across multiple machines, and clean reversion if needed.

**When Would You Need to Modify a Package?**

Some real-world scenarios where modifying a package is useful:

* **Updating a package before official release:** If a new version of **Social-Engineer Toolkit (SET)** is available but Kali developers are unavailable, you can update the package yourself.
* **Debugging issues:** When troubleshooting **MIFARE NFC card** issues, rebuilding `libfreefare` with debug messages enabled helps gather actionable data for bug reports.
* **Applying fixes from upstream repositories:** If **Pyrit** fails with an error, and you find a fix in its GitHub repository, you can rebuild the package with the patch applied.

**General Process for Modifying a Package**

Regardless of the modification, the process remains the same:

1. **Retrieve the source package.**
2. **Extract its contents.**
3. **Make the necessary changes.**
4. **Rebuild the package.**

There are multiple tools available for each step, and while the most relevant ones are discussed, the exact approach may vary depending on the situation. If issues arise, troubleshooting through appropriate forums or documentation is recommended.

### 10.1.1. Getting the Sources

Rebuilding a Kali package begins with obtaining its source code. A **source package** consists of multiple files, with the most critical being the **.dsc (Debian Source Control)** file. This file lists other necessary components such as `.tar.{gz,bz2,xz}` and sometimes `.diff.gz` or `.debian.tar.{gz,bz2,xz}` files.

**Retrieving Source Packages from Kali Mirrors**

* Kali source packages are stored on publicly accessible mirrors.
* The easiest way to download them is by using the command:

  ```bash
  apt source package_name
  ```
* This requires adding a `deb-src` line to `/etc/apt/sources.list` and updating the package index with `apt update`.

For example, running:

```bash
apt source libfreefare
```

retrieves the package and extracts its contents, creating a directory (`libfreefare-0.4.0`) containing both the package source files and a `debian/` folder with packaging metadata.

**Downloading Specific Versions**

If a required version is unavailable in the repositories, it can be downloaded manually using **dget**:

```bash
dget URL_of_the_.dsc_file
```

This fetches the `.dsc` file and all referenced files, allowing manual extraction using:

```bash
dpkg-source -x package.dsc
```

If the signature check fails, extraction can be forced with the `--allow-unauthenticated` or `-u` option.

**Retrieving Sources from Git**

* Some packages are maintained in Git repositories, either on Debian's infrastructure or **Kali’s GitLab** (`gitlab.com/kalilinux/packages`).
* To clone a Kali package repository:

  ```bash
  git clone https://gitlab.com/kalilinux/packages/package-name.git
  ```
* Unlike `apt source`, Git repositories do not have patches applied automatically. Check the `debian/patches/` directory for applied modifications.

By obtaining sources through `apt source`, `dget`, or Git, users can modify and rebuild packages to suit their needs.

### 10.1.2. Installing Build Dependencies

Once the source package is obtained, the next step is installing its **build dependencies**. These dependencies are required to compile the package and are often necessary for testing partial builds while making modifications.

**Identifying Build Dependencies**

* Each source package lists its required dependencies in the **Build-Depends** field of the `debian/control` file.
* The easiest way to install them is using:

  ```bash
  sudo apt build-dep ./
  ```

  This command reads the `Build-Depends` field and installs all necessary packages.

### 10.1.3. Making Changes

#### **Modifying a Package**

Before rebuilding a package, you should **change the version number** to differentiate it from the official versions. This is done using `dch` (Debian Changelog) from the `devscripts` package:

```bash
dch --local yourname
```

This opens the `debian/changelog` file in an editor, where you document the changes.

Example:

```bash
libfreefare (0.4.0-2yourname1) UNRELEASED; urgency=medium

  * Enable --with-debug configure option.

 -- Your Name <your.email@example.com>  Fri, 22 Jan 2021 10:36:00 -0400
```

To avoid manually entering your name/email each time, set:

```bash
export DEBFULLNAME="Your Name"
export DEBEMAIL="your.email@example.com"
```

***

#### **Applying a Patch**

If you need to patch a package, do the following:

1. Download and unpack the source:

   ```bash
   apt source packagename
   cd packagename-version/
   ```
2. Download and apply the patch:

   ```bash
   wget https://example.com/patch.diff -O /tmp/mypatch.diff
   patch -p1 < /tmp/mypatch.diff
   ```
3. If the package uses the `3.0 (quilt)` format, register the patch:

   ```bash
   dpkg-source --commit
   ```

   You'll be prompted to name the patch, e.g., `fix-bug.patch`, which gets stored in `debian/patches/`.
4. Verify:

   ```bash
   tail -n 1 debian/patches/series
   ```

For Git-based packaging, tools like `git-buildpackage` (`gbp pq`) or `git-dpm` manage patches differently.

***

#### **Tweaking Build Options**

Modify `debian/rules` to adjust build options. For example, enabling debug mode in `libfreefare`:

```makefile
override_dh_auto_configure:
  dh_auto_configure -- --without-cutter --disable-silent-rules --enable-debug
```

If `dh` is used, overrides may be needed for `dh_auto_configure` or `dh_auto_build`.

***

#### **Packaging a New Upstream Version**

To package a new version (e.g., updating `SET` from `7.4.4` to `7.4.5`):

1. Download and extract the new source:

   <pre class="language-bash" data-overflow="wrap"><code class="lang-bash">wget https://github.com/trustedsec/social-engineer-toolkit/archive/7.4.5.tar.gz -O set_7.4.5.orig.tar.gz
   tar xvf set_7.4.5.orig.tar.gz
   </code></pre>
2. Copy over Debian packaging files:

   ```bash
   cp -a set-7.4.4/debian social-engineer-toolkit-7.4.5/debian
   cd social-engineer-toolkit-7.4.5
   ```
3. Update the changelog:

   ```bash
   dch -v 7.4.5-0yourname1 "New upstream release"
   ```

At this point, you can build the updated package.

### 10.1.4. Starting the Build

Once all necessary changes have been applied to the source package, you can proceed with building the actual `.deb` binary package.

***

#### **1. Building the `.deb` Package**

Use the `dpkg-buildpackage` command to generate the `.deb` files:

```bash
dpkg-buildpackage -us -uc -b
```

* `-us`: Skips signing the source package (`.dsc`) file.
* `-uc`: Skips signing the `.changes` file.
* `-b`: Performs a **binary-only build** (no source package is created).

This process will generate multiple `.deb` files in the **parent directory** of the source package.

Example output:

{% code overflow="wrap" %}

```plaintext
dpkg-deb: building package 'libfreefare0' in '../libfreefare0_0.4.0-2yourname1_amd64.deb'.
dpkg-deb: building package 'libfreefare-bin' in '../libfreefare-bin_0.4.0-2yourname1_amd64.deb'.
dpkg-deb: building package 'libfreefare-doc' in '../libfreefare-doc_0.4.0-2yourname1_all.deb'.
```

{% endcode %}

***

#### **2. Installing the Newly Built Package**

After building the package, install it using `apt install` (preferred over `dpkg -i` because it handles dependencies better):

```bash
sudo apt install ../libfreefare0_0.4.0-2yourname1_amd64.deb \
                 ../libfreefare-bin_0.4.0-2yourname1_amd64.deb
```

If `apt` refuses due to missing dependencies, you can try:

```bash
sudo apt --fix-broken install
```

or

```bash
sudo apt install -f
```

Alternatively, you can install the package using `dpkg -i`:

```bash
sudo dpkg -i ../libfreefare0_0.4.0-2yourname1_amd64.deb
```

If `dpkg -i` fails due to missing dependencies, resolve them with:

```bash
sudo apt -f install
```

***

#### **3. Using `debuild` for a More Thorough Build**

Debian developers often use `debuild`, which wraps around `dpkg-buildpackage` and performs additional checks:

```bash
debuild -us -uc -b
```

This command:

* Runs `dpkg-buildpackage` normally.
* Uses `lintian` to check the package for policy violations.
* Cleans the build environment to prevent local settings from affecting the build.

## 10.2. Recompiling the Linux Kernel

Kali Linux provides a fully featured kernel with the widest hardware support possible. However, some users may prefer to recompile the kernel to optimize performance, reduce memory usage, or apply custom patches.

**Reasons for Recompiling the Kernel**

1. **Performance Optimization**
   * The default kernel includes many drivers and features, which take up **physical memory** even if they are never used.
   * Removing unused modules can **reduce memory consumption** and improve system performance.
2. **Security Hardening**
   * Fewer features and drivers mean a **smaller attack surface** for potential vulnerabilities.
   * A minimal custom kernel reduces the risk of kernel exploits affecting your system.
3. **Custom Features and Patches**
   * Some kernel features or patches are **not included** in the standard Kali kernel (e.g., custom security modules, experimental features).
   * A custom kernel allows **fine-tuned control** over its behavior.

**⚠️ Important Warning**

* **Security Updates Responsibility**:
  * When you compile your own kernel, **you are responsible** for keeping it up to date.
  * Kali cannot provide security updates for custom-compiled kernels.
* **Alternative**:
  * If you want a secure and maintained system, it's best to use **the official Kali kernel** instead of a custom one.

### 10.2.1. Introduction and Prerequisites

* Debian and Kali manage the kernel as a package rather than the traditional method of compiling and installing kernels manually. This approach keeps the kernel under the control of the packaging system, allowing for easy removal and deployment across multiple machines.
* The associated package scripts handle interactions with the bootloader and the initrd generator automatically.
* The upstream Linux sources include everything needed to build a Debian kernel package. However, additional packages must be installed to ensure a successful build.
  * The `build-essential` package provides the necessary compilation tools.
  * The `libncurses5-dev` package is required for the kernel configuration step.
  * The `fakeroot` package allows the creation of the Debian package without requiring administrative privileges.
* To install these dependencies, use the following command:

```
# apt install build-essential libncurses5-dev fakeroot
```

### 10.2.2. Getting the Sources

* The Linux kernel sources are available as a package and can be retrieved by installing the **linux-source-version** package. To list the latest kernel version packaged by Kali, use:

  ```bash
  apt-cache search ^linux-source
  ```
* The source code in these packages differs slightly from the versions published by Linus Torvalds and the kernel developers. Debian and Kali apply various patches, including:
  * Backported fixes, features, and drivers from newer kernel versions.
  * New features not yet merged into the upstream Linux tree.
  * Debian or Kali-specific modifications.
* The section focuses on **Linux kernel 4.9**, but the same process can be adapted for other versions.
* To install the **linux-source-4.9** package, run:

  ```bash
  apt install linux-source-4.9
  ```
* The installation also includes **bc** and **libreadline7**, with suggested packages like **libncurses-dev** and **libqt4-dev**.
* After installation, check the source package location:

  ```bash
  ls /usr/src
  ```

  This lists files such as:

  * `linux-config-4.9`
  * `linux-patch-4.9-rt.patch.xz`
  * `linux-source-4.9.tar.xz` (a compressed archive of the kernel sources)
* The kernel sources should be extracted into a new directory (not directly under `/usr/src/`, as no special permissions are required). Instead, create and navigate to a directory like `~/kernel/`:

  ```bash
  mkdir ~/kernel; cd ~/kernel
  tar -xaf /usr/src/linux-source-4.9.tar.xz
  ```

### 10.2.3. Configuring the Kernel

* Configuring the kernel is the next step, and the process depends on specific goals.
* The kernel build relies on a **kernel configuration file**. Typically, it's best to stay as close as possible to Kali's default configuration, which is stored in the `/boot` directory.
* To copy the current configuration file:
  1. Find the kernel version using:

     ```bash
     uname -r
     ```
  2. Copy the configuration file to the kernel source directory:

     ```bash
     cp /boot/config-4.9.0-kali1-amd64 ~/kernel/linux-source-4.9/.config
     ```
* Alternatively, default kernel configurations are available in `arch/arch/configs/*_defconfig`. Use:
  * `make x86_64_defconfig` for **64-bit PCs**
  * `make i386_defconfig` for **32-bit PCs**
* If no changes are needed, you can **skip to compiling and building the package**. However, if you want to modify or fully reconfigure the kernel, use one of the available configuration interfaces:
  * **Text-mode interface:**

    ```bash
    make menuconfig
    ```

    * Requires the **libncurses5-dev** package.
    * Provides a hierarchical menu to navigate kernel options.
    * Use arrow keys to move, **Space** to toggle options, and **Enter** to confirm selections.
    * **Exit** saves changes if confirmed.
  * **Graphical interfaces:**
    * `make xconfig` (requires **libqt4-dev**) – Qt-based GUI
    * `make gconfig` (requires **libglade2-dev** and **libgtk2.0-dev**) – GTK+ GUI

#### **Dealing with Outdated `.config` Files**

* If using a `.config` file from an older kernel version, it must be updated:
  * `make oldconfig` – Interactively prompts for new configuration options.
  * `make olddefconfig` – Automatically selects default answers for new options.
  * `make oldnoconfig` – Automatically selects **"no"** for all new options.

### 10.2.4. Compiling and Building the Package

* Before rebuilding the kernel, it's important to clean up previous compilations:
  * `make clean` removes compiled files but keeps configuration files.
  * `make distclean` removes even more generated files, including `.config`. **Backup `.config` before using this command.**
* Once the kernel configuration is finalized, **use `make deb-pkg` to generate Debian packages** in `.deb` format. This command creates up to five packages:
  * `linux-image-version` – Contains the kernel image and modules.
  * `linux-headers-version` – Provides header files for building external modules.
  * `linux-firmware-image-version` – Contains firmware files for certain drivers (may be missing when using Debian/Kali sources).
  * `linux-image-version-dbg` – Includes debugging symbols for the kernel and modules.
  * `linux-libc-dev` – Provides headers for user-space libraries like glibc.
* The kernel version is defined using variables from the **Makefile** (`VERSION`, `PATCHLEVEL`, `SUBLEVEL`, `EXTRAVERSION`), along with `LOCALVERSION` and `LOCALVERSION` environment variables. The package version follows the same version string but includes a revision number stored in `.version` (unless overridden with `KDEB_PKGVERSION`).
* Example command to build the kernel package:

  ```bash
  make deb-pkg LOCALVERSION=-custom KDEB_PKGVERSION=$(make kernelversion)-1
  ```
* After building, check for generated `.deb` files:

  ```bash
  ls ../*.deb
  ```

  Example output:

  ```
  ../linux-headers-4.9.0-kali1-custom_4.9.2-1_amd64.deb  
  ../linux-image-4.9.0-kali1-custom_4.9.2-1_amd64.deb  
  ../linux-image-4.9.0-kali1-custom-dbg_4.9.2-1_amd64.deb  
  ../linux-libc-dev_4.9.2-1_amd64.deb  
  ```
* To install the compiled kernel, use `dpkg -i`:

  ```bash
  dpkg -i file.deb
  ```

  * The **`linux-image`** package is mandatory.
  * The **`linux-headers`** package is needed **only if** you need to build external modules (e.g., if you have `*-dkms` packages installed).
  * The other packages are **optional** unless explicitly required. To check for installed `*-dkms` packages, run:

    ```bash
    dpkg -l "*-dkms" | grep ^ii
    ```

## 10.3. Building Custom Kali Live ISO Images

* **Kali Linux** provides extensive functionality and flexibility out of the box, allowing users to perform advanced tasks with the right knowledge and practice.
* **Customization** is possible to tailor a Kali build with specific files or packages, scaling performance and features as needed. Custom builds can also automate certain functions.
* **Examples of custom Kali builds** include:
  * **Kali ISO of Doom** – A highly customized live Kali ISO.
  * **Kali Evil Wireless Access Point** – A specialized Kali build for penetration testing wireless networks.
* **Rolling a custom Kali ISO image** involves using **live-build**, a script suite that automates and customizes every aspect of ISO creation.
* **Live-build setup:**
  * It relies on a structured directory as input for configuration.
  * The **live-build-config Git repository** stores configurations and helper scripts, serving as the foundation for building customized Kali images.
* **Important Note:**
  * These commands **must be executed on an up-to-date Kali Linux system**.
  * Running them on a **non-Kali system** or an **outdated Kali installation** will likely result in failures.

### 10.3.1. Installing Pre-Requisites

* The first step in creating a **custom Kali ISO** is to install the required packages and retrieve the **Kali live-build configuration** from Git.
* Install the necessary packages:

  ```bash
  apt install curl git live-build
  ```
* Clone the **live-build configuration repository**:

  ```bash
  git clone https://gitlab.com/kalilinux/build-scripts/live-build-config.git
  ```
* Navigate to the cloned directory and list its contents:

  ```bash
  cd live-build-config
  ls
  ```

  Example output:

  ```
  auto  bin  build_all.sh  build.sh  kali-config  README.md  simple-cdd
  ```
* At this point, an **updated but unmodified Kali live ISO** can be created by running:

  ```bash
  ./build.sh --verbose
  ```

  * The process takes a long time since it downloads all necessary packages.
  * Once completed, the **new ISO image** will be available in the `images` directory.

### 10.3.2. Building Live Images with Different Desktop Environments

* The `build.sh` script is a **wrapper for live-build**, responsible for setting up the `config` directory that **live-build** requires.
* It applies different configurations based on the `--variant` option.
* The **config directory** is created by merging files from:
  * `kali-config/common` (shared configuration).
  * `kali-config/variant-X` (where `X` is the specified variant).
* If no `--variant` option is provided, the **default** variant is used.
* The `kali-config` directory includes configurations for different desktop environments:
  * `e17` – **Enlightenment**
  * `gnome` – **GNOME**
  * `i3wm` – **i3 Window Manager**
  * `kde` – **KDE**
  * `lxde` – **LXDE**
  * `mate` – **MATE Desktop**
  * `xfce` – **Xfce**
* To build a **Kali live ISO with KDE**, run:

  ```bash
  ./build.sh --variant kde --verbose
  ```
* **Further customization**:
  * The **variant system** enables predefined customizations.
  * **Advanced modifications** can be made by editing files in `kali-config` subdirectories.
  * Reading the **Debian Live System Manual** provides deeper insights into custom image configurations.
* The following sections will cover specific examples of customization.

### 10.3.3. Changing the Set of Installed Packages

* **Package Lists (`package-lists/*.list.chroot`)**
  * The default configuration uses `package-lists/kali.list.chroot`, which includes the **`kali-linux-default`** metapackage.
  * To customize your build, you can:
    * **Comment out `kali-linux-default`** and select a different metapackage.
    * **Manually specify individual packages** instead of relying on a metapackage.
    * **Use a mix**—start with a metapackage and add additional packages.
* **Adding Custom Packages (`packages.chroot/`)**
  * Only packages available in the **official Kali repository** can be included in `package-lists/*.list.chroot`.
  * If you have custom `.deb` files, place them in:

    ```
    kali-config/config-<variant>/packages.chroot/
    ```

    * Example: For a **GNOME variant**, store `.deb` files in:

      ```
      kali-config/config-gnome/packages.chroot/
      ```

***

#### **Using Kali Metapackages for Custom Builds**

**Metapackages** are **empty** packages that install multiple related tools via dependencies. This makes it easy to install predefined toolsets.

**Core System Metapackages**

| Metapackage             | Description                                       |
| ----------------------- | ------------------------------------------------- |
| `kali-linux-core`       | Base system (included in all other metapackages). |
| `kali-linux-headless`   | Command-line tools only (no GUI).                 |
| `kali-linux-default`    | Standard Kali installation (CLI + GUI).           |
| `kali-linux-large`      | Includes extra tools beyond the default.          |
| `kali-linux-everything` | **All** Kali tools (\~50GB+).                     |

**Specialized Toolset Metapackages**

| Metapackage                    | Focus Area                                         |
| ------------------------------ | -------------------------------------------------- |
| `kali-tools-top10`             | The **10 most popular** penetration testing tools. |
| `kali-tools-web`               | Web app penetration testing tools.                 |
| `kali-tools-passwords`         | Password cracking tools.                           |
| `kali-tools-wireless`          | **WiFi, Bluetooth, RFID, and SDR** security tools. |
| `kali-tools-forensics`         | Digital forensics and incident response tools.     |
| `kali-tools-802-11`            | Wireless security assessment tools.                |
| `kali-tools-bluetooth`         | Bluetooth security tools.                          |
| `kali-tools-crypto-stego`      | Cryptography & **steganography** tools.            |
| `kali-tools-crypto-fuzzing`    | **Fuzzing attack** tools.                          |
| `kali-tools-gpu`               | Tools leveraging **GPU acceleration**.             |
| `kali-tools-hardware`          | Hardware hacking tools.                            |
| `kali-tools-rfid`              | RFID security tools.                               |
| `kali-tools-sdr`               | **Software Defined Radio (SDR)** tools.            |
| `kali-tools-voip`              | **Voice-over-IP (VoIP)** assessment tools.         |
| `kali-tools-windows-resources` | Precompiled **Windows binaries** for pentesting.   |

* **Full List of Metapackages**:\
  🔗 <https://tools.kali.org/kali-metapackages>

#### **Debconf Preseeding (Automated Package Configuration)**

* **Preseeding** allows you to configure package settings automatically **before installation**.
* Preseed files should be placed in:

  ```
  preseed/*.cfg
  ```
* This helps automate **user input** (e.g., setting passwords, enabling features, disabling prompts).

#### **Example: Custom Kali ISO with Wireless Tools and Preseed Configuration**

1. Clone the Kali live-build repository:

   ```bash
   git clone https://gitlab.com/kalilinux/build-scripts/live-build-config.git
   cd live-build-config
   ```
2. Modify the package list (`package-lists/kali.list.chroot`):

   ```bash
   echo "kali-tools-wireless" >> package-lists/kali.list.chroot
   ```
3. Add custom `.deb` packages:

   ```bash
   mkdir -p kali-config/config-gnome/packages.chroot
   cp my-custom-tool.deb kali-config/config-gnome/packages.chroot/
   ```
4. Create a **preseed configuration** (`preseed/custom.cfg`):

   ```bash
   echo "d-i passwd/root-password password toor" > preseed/custom.cfg
   echo "d-i passwd/root-password-again password toor" >> preseed/custom.cfg
   ```
5. Build the custom ISO:

   ```bash
   ./build.sh --variant gnome --verbose
   ```

### 10.3.4. Using Hooks to Tweak the Contents of the Image

* **Live-build Hooks**: These are scripts that execute at different stages of the build process.
* **Chroot Hooks**:
  * Placed in `hooks/live/*.chroot`.
  * Execute inside the chroot environment during the build process.
  * Chroot temporarily changes the root directory to an alternate filesystem tree.
  * Since applications in chroot cannot access files outside, chroot hooks are limited to modifying the chroot environment.
  * Kali Linux uses chroot hooks for various customizations (e.g., `kali-config/common/hooks/live/kali-hacks.chroot`).

The **Binary Hooks** execute later in the build process. They run in the build environment rather than in a chrooted environment. These scripts:

* Are located in `hooks/live/*.binary`.
* Execute at the end of the build process.
* Modify the ISO image but not the live filesystem since it is already built.
* In Kali Linux, binary hooks adjust the `isolinux` configuration.
* Example: `kali-config/common/hooks/live/persistence.binary` adds boot menu entries for persistence.

### 10.3.5. Adding Files in the ISO Image or in the Live Filesystem

* **Adding Files to the Live File System**:
  * Files should be placed in `includes.chroot` at their intended locations.
  * Example: `kali-config/common/includes.chroot/usr/lib/live/config/0031-kali-password` appears as `/usr/lib/live/config/0031-kali-password` in the live file system.
* **Live-Boot Hooks**:
  * Stored in `/lib/live/config/XXXX-name`.
  * Executed by the `init` script of the `live-boot` package.
  * Modify system behavior at runtime to suit a live environment.
  * Can be used to implement custom boot parameters.
* **Adding Files to the ISO Image**:
  * Files should be placed in `includes.binary` at their intended locations.
  * Example: `kali-config/common/includes.binary/isolinux/splash.png` replaces `/isolinux/splash.png` in the ISO filesystem, changing the Isolinux bootloader background.

## 10.4.1. The Persistence Feature: Explanations

* **Persistence Feature Overview**:
  * A live system is ephemeral—data and changes are lost after reboot.
  * **Persistence** allows saving data across reboots using the `persistence` boot parameter.
* **Enabling Persistence**:
  * Kali live images include two default boot menu entries:
    * **Live USB Persistence**
    * **Live USB Encrypted Persistence**
* **How Persistence Works**:
  * `live-boot` scans all partitions for filesystems labeled **persistence**.
  * The label can be changed using the `persistence-label=value` boot parameter.
  * Persistence is configured using a **persistence.conf** file on the partition.
  * Each line in **persistence.conf** specifies a directory to be made persistent.
  * The special value **"/ union"** enables full persistence using a **union mount**, which stores only changes compared to the underlying filesystem.
  * The data of persisted directories is saved in the filesystem containing the **persistence.conf** file.

### 10.4.2. Setting Up Unencrypted Persistence on a USB Key

* **Prerequisites**:
  * A **Kali live USB** prepared following the instructions.
  * A **USB key** large enough (at least **4GB** for the ISO and persistent data).
  * The USB key is detected as `/dev/sdb` and contains **two partitions** (`/dev/sdb1` and `/dev/sdb2`).
  * **Caution**: Re-partitioning the wrong drive can result in **data loss**.
* **Creating a New Partition for Persistence**:
  * Determine the **size of the ISO image**:

    ```bash
    parted /dev/sdb print
    du --block-size=1MB kali-linux-2020.3-live-amd64.iso | awk '{print $1}'
    ```
  * Example output: `Size of image is 3518 MB`.
  * Create a **new partition** after the live image:

    ```bash
    parted -a optimal /dev/sdb mkpart primary "3518MB" 100%
    ```
  * Verify the partition:

    ```bash
    parted /dev/sdb print
    ```
  * The new partition (`/dev/sdb3`) should now be available.
* **Formatting and Configuring Persistence**:
  * Format the new partition with an **ext4 filesystem** labeled `persistence`:

    ```bash
    mkfs.ext4 -L persistence /dev/sdb3
    ```
  * Mount the partition and create the `persistence.conf` file:

    ```bash
    mount /dev/sdb3 /mnt
    echo "/ union" > /mnt/persistence.conf
    ls -l /mnt
    ```
  * Example output:

    ```
    luaCopyEdittotal 20
    drwx------ 2 root root 16384 May 10 13:31 lost+found
    -rw-r--r-- 1 root root     8 May 10 13:34 persistence.conf
    ```
  * Unmount the partition:

    ```bash
    bashCopyEditumount /mnt
    ```
* **Booting with Persistence**:
  * The USB key is now **ready** for use.
  * Boot using the **"Live USB Persistence"** menu entry.

### 10.4.3. Setting Up Encrypted Persistence on a USB Key

* **Encrypted Persistence Overview**:
  * `live-boot` supports **persistence on encrypted partitions**.
  * Data is protected using a **LUKS encrypted partition**.
  * The initial steps (partition creation) are **the same** as non-encrypted persistence.
  * Instead of formatting with `ext4`, the partition is **initialized as a LUKS container**.
  * A **virtual partition** is created by `cryptsetup` under `/dev/mapper/`, which represents the **decrypted content**.
* **Steps to Set Up Encrypted Persistence**:
  1. **Initialize the LUKS container**:

     ```bash
     cryptsetup --verbose --verify-passphrase luksFormat /dev/sdb3
     ```

     * **Warning**: This **overwrites all data** on `/dev/sdb3`.
     * Enter and confirm the **passphrase**.
  2. **Open the encrypted partition**:

     ```bash
     cryptsetup luksOpen /dev/sdb3 kali_persistence
     ```

     * Decrypted partition is now available as `/dev/mapper/kali_persistence`.
  3. **Format the decrypted partition with ext4**:

     ```bash
     mkfs.ext4 -L persistence /dev/mapper/kali_persistence
     ```
  4. **Create and configure persistence.conf**:

     ```bash
     mount /dev/mapper/kali_persistence /mnt
     echo "/ union" > /mnt/persistence.conf
     umount /mnt
     ```
  5. **Close the encrypted container**:

     ```bash
     cryptsetup luksClose /dev/mapper/kali_persistence
     ```
* **Booting with Encrypted Persistence**:
  * Use the **"Live USB Encrypted Persistence"** boot menu entry.
  * You will be prompted for the **passphrase** to unlock the encrypted persistence.

### 10.4.4. Using Multiple Persistence Stores

**Multiple Persistence Filesystems**

* **Use-case**: Different persistence setups for different needs.
* **Solution**: Use multiple persistence filesystems with different labels and specify which one to use with `persistence-label=label`.

**Example Scenario**

* A **pen-tester** needs:
  * An **encrypted** persistence partition for work data (**"work"**)
  * An **unencrypted** persistence partition for demo materials (**"demo"**)
* A **custom Kali live image** is built with dedicated boot menu entries.

**Customizing Boot Menu**

* Modify `kali-config/common/hooks/live/persistence-menu.binary`:

  ```sh
  #!/bin/sh

  if [ ! -d isolinux ]; then
      cd binary
  fi

  cat >>isolinux/live.cfg <<END
  label live-demo
      menu label ^Live USB with Demo Data
      linux /live/vmlinuz
      initrd /live/initrd.img
      append boot=live username=root hostname=kali persistence-label=demo persistence

  label live-work
      menu label ^Live USB with Work Data
      linux /live/vmlinuz
      initrd /live/initrd.img
      append boot=live username=root hostname=kali persistence-label=work persistence-encryption=luks persistence
  END
  ```
* This creates two boot menu entries:
  * **Live USB with Demo Data** (unencrypted)
  * **Live USB with Work Data** (encrypted)

***

#### **Creating the Partitions**

* **Step 1: Partition the USB drive** (assume `/dev/sdb` and ISO size = **3000 MB**)

  ```bash
  parted /dev/sdb mkpart primary 3000MB 55%
  parted /dev/sdb mkpart primary 55% 100%
  ```
* **Step 2: Setup the unencrypted "demo" partition**

  ```bash
  mkfs.ext4 -L demo /dev/sdb3
  mount /dev/sdb3 /mnt
  echo "/ union" > /mnt/persistence.conf
  umount /mnt
  ```
* **Step 3: Setup the encrypted "work" partition**

  ```bash
  cryptsetup --verbose --verify-passphrase luksFormat /dev/sdb4
  cryptsetup luksOpen /dev/sdb4 kali_persistence
  mkfs.ext4 -L work /dev/mapper/kali_persistence
  mount /dev/mapper/kali_persistence /mnt
  echo "/ union" > /mnt/persistence.conf
  umount /mnt
  cryptsetup luksClose /dev/mapper/kali_persistence
  ```
* **Final Result**:
  * On boot, you can select **"Live USB with Demo Data"** for the unencrypted setup.
  * Select **"Live USB with Work Data"** for the encrypted persistence setup.

***

#### **Adding a Nuke Password for Extra Safety**

* **Purpose**: Securely erase encrypted data in case of emergency.
* **How It Works**: Enter a **nuke password** instead of the real one, and it will delete all encryption keys, making data **irrecoverable**.
* **Setup** (after installing `cryptsetup-nuke-password` package):

  ```bash
  bashCopyEditdpkg-reconfigure cryptsetup-nuke-password
  ```
* **Important**: Backup encryption keys before using the nuke feature.

**More Info**: [Kali Linux Nuke Password Guide](https://www.kali.org/tutorials/nuke-kali-linux-luks/)

## 10.5. Summary

#### **Modifying Kali Packages (10.5.1)**

**Overview**:

* Modifying Kali packages is often done by Kali contributors, but you may need to build custom packages for specific use cases or deployment needs.
* The process involves downloading source packages, making modifications, and rebuilding the package.

**Steps for Modifying a Package**:

1. **Obtain Source Package**:
   * Use `apt source source-package-name` or `dget` (for direct `.dsc` downloads) to get the package source.
   * For Kali-specific packages, use Git:

     ```bash
     git clone https://gitlab.com/kalilinux/packages/source-package.git
     ```
2. **Install Build Dependencies**:
   * Run `sudo apt build-dep ./` to install the necessary dependencies.
3. **Make Modifications**:
   * Update the version with `dch --local version-identifier`.
   * Apply patches using `patch` or modify quilt's patch series.
   * Tweak build options in the `debian/rules` file.
4. **Build the Package**:
   * Run `dpkg-buildpackage -us -uc -b` from the source directory to build the package.
   * Install it with `dpkg -i package-name_version_arch.deb`.

***

#### **Recompiling the Kali Kernel (10.5.2)**

**Overview**:

* Recompiling the Kali kernel is an advanced task, often done to add custom features, non-standard drivers, or patches.
* Kernel modifications can destabilize your system, and Kali won't ensure security updates for custom kernels.

**Steps for Recompiling the Kernel**:

1. **Install Required Packages**:

   ```bash
   sudo apt install build-essential libncurses5-dev fakeroot
   ```
2. **Download Kernel Source**:
   * List available kernel versions with `apt-cache search ^linux-source`.
   * Install the desired kernel source:

     ```bash
     sudo apt install linux-source-version-number
     ```
3. **Extract the Source**:
   * Extract the kernel source using `tar -xaf`.
4. **Configure the Kernel**:
   * For a standard configuration, copy Kali’s config file:

     ```bash
     cp /boot/config-version-string ~/kernel/linux-source-version-number/.config
     ```
   * Use `make menuconfig` for configuration options.
5. **Compile the Kernel**:
   * Clean previous builds with `make clean`.
   * Build the Debian packages with `make deb-pkg`.
6. **Install the Kernel**:
   * Install the kernel with `dpkg -i linux-image-version.deb`.

***

#### **Building Custom Kali Live ISO Images (10.5.3)**

**Overview**:

* Kali Live ISOs are built using live-build, a set of scripts for customizing and automating the ISO creation process.
* Customization can include adding/removing packages, adding files, or running scripts during boot or chroot setup.

**Steps for Building a Custom ISO**:

1. **Install Required Tools**:

   ```bash
   sudo apt install curl git live-build
   ```
2. **Clone the Live-build Configuration**:

   ```bash
   git clone https://gitlab.com/kalilinux/build-scripts/live-build-config.git
   ```
3. **Build the ISO**:
   * To build the ISO:

     ```bash
     ./build.sh --verbose
     ```
   * For a specific variant (e.g., Xfce), use:

     ```bash
     ./build.sh --variant xfce
     ```
4. **Customize the ISO**:
   * **Add/Remove Packages**: Modify files in `package-lists/*.list.chroot`.
   * **Include Custom Packages**: Place `.deb` files in `packages.chroot`.
   * **Add Files**: Place files in `includes.chroot` to copy to the live filesystem.
   * **Add Scripts**:
     * Run scripts during chroot setup with `hooks/live/*.chroot`.
     * Run scripts at boot by placing them in `/usr/lib/live/config/XXXX-name`.
5. **Encrypted and Unencrypted Persistence**:
   * Use live-build to set up both encrypted and unencrypted persistence on a USB key.

***

***

***

**`Hacker's Mantra:`**` ``Every lock has a key. The trick is knowing where to find it. -- Gabriella Coleman`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.rootkid.in/exam-prep-notes/klcp-exam-pen-103-notes/10.-advanced-usage.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
