---
gitea: none
include_toc: true
---
[![Static Badge](https://badges.coresecret.dev/badge/Release-V8.13.272.2025.10.22-white?style=plastic&logo=linux&logoColor=white&logoSize=auto&label=Release&color=%23FCC624)](https://git.coresecret.dev/msw/CISS.debian.live.builder)
&nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/Licence-EUPL1.2-white?style=plastic&logo=europeanunion&logoColor=white&logoSize=auto&label=Licence&color=%23003399)](https://eupl.eu/1.2/en/) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/opensourceinitiative-Compliant-white?style=plastic&logo=opensourceinitiative&logoColor=white&logoSize=auto&label=OSI&color=%233DA639)](https://opensource.org/license/eupl-1-2) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/Bash-V5.2.37-white?style=plastic&logo=gnubash&logoColor=white&logoSize=auto&label=Bash&color=%234EAA25)](https://www.gnu.org/software/bash/) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/shellcheck-passed-white?style=plastic&logo=gnubash&logoColor=white&logoSize=auto&label=shellcheck&color=%234EAA25)](https://shellcheck.net/) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/shellformat-passed-white?style=plastic&logo=google&logoColor=white&logoSize=auto&label=shellformat&color=%234285F4)](https://github.com/mvdan/sh) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/Shellstyle-Google-white?style=plastic&logo=google&logoColor=white&logoSize=auto&label=Shellstyle&color=%234285F4)](https://google.github.io/styleguide/shellguide.html)
&nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/Gitea-1.24.6-white?style=plastic&logo=gitea&logoColor=white&logoSize=auto&label=gitea&color=%23609926)](https://docs.gitea.com/) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/IntelliJ-2025.2.3-white?style=plastic&logo=intellijidea&logoColor=white&logoSize=auto&label=IntelliJ&color=%23000000)](https://www.jetbrains.com/store/?section=personal&billing=yearly) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/keepassxc-2.7.10-white?style=plastic&logo=keepassxc&logoColor=white&logoSize=auto&label=KeePassXC&color=%236CAC4D)](https://keepassxc.org/) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/netcup-Netcup-white?style=plastic&logo=netcup&logoColor=white&logoSize=auto&label=powered&color=%23056473)](https://www.netcup.com/de) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/powered-Centurion-white?style=plastic&logo=europeanunion&logoColor=white&logoSize=auto&label=powered&color=%230F243E)](https://coresecret.eu/) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/SocialMedia-@coresecret_eu-white?style=plastic&logo=x&logoColor=white&logoSize=auto&label=SocialMedia&color=%23000000)](https://x.com/coresecret_eu) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/Donation-Donation-white?style=plastic&logo=sepa&logoColor=white&logoSize=auto&label=&color=%230F243E)](https://coresecret.eu/spenden/#sepa) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/bitcoin-Bitcoin-white?style=plastic&logo=bitcoin&logoColor=white&logoSize=auto&label=Donation&color=%23F7931A)](https://coresecret.eu/spenden/#bitcoin) &nbsp;
[![Static Badge](https://badges.coresecret.dev/badge/simplex-Simplex-white?style=plastic&logo=simplex&logoColor=white&logoSize=auto&label=Contact&color=%23000000)](https://coresecret.eu/contact/#simplex) &nbsp;

# 1. CISS.debian.live.builder

**Centurion Intelligence Consulting Agency Information Security Standard**<br>
*Debian Live Build Generator for hardened live environment and CISS Debian Installer*<br>
**Master Version**: 8.13<br>
**Build**: V8.13.272.2025.10.22<br>

This shell wrapper automates the creation of a Debian Bookworm live ISO hardened according to the latest best practices in server
and service security. It integrates into your build pipeline to deliver an isolated, robust environment suitable for
cloud deployment or unattended installations via the forthcoming `CISS.debian.installer`. Additionally, automated CI workflows 
based on Gitea Actions are provided, enabling reproducible ISO generation. A generic ISO is automatically built upon significant
changes and made publicly available for download. The latest generic ISO is available at:
**[PUBLIC CISS.debian.live.ISO](/docs/DL_PUB_ISO.md)**

Check out more:
* [CenturionNet Services](https://coresecret.eu/cnet/) 
* [CenturionDNS Resolver](https://eddns.eu/)
* [CenturionDNS Blocklist](https://dns.eddns.eu/blocklists/centurion_titanium_ultimate.txt) 
* [CenturionNet Status](https://uptime.coresecret.eu/) 
* [CenturionMeet](https://talk.e2ee.li/) 
* [Contact the author](https://coresecret.eu/contact/)

## 1.1. Preliminary Remarks

### 1.1.1. HSM
Please note that all my signing keys are stored in an HSM and that the signing environment is air-gapped. The next step is to 
move to a room-gapped environment. ^^

### 1.1.2. DNSSEC, HSTS, TLS

Please note that `coresecret.dev` is included in the [(HSTS Preload List)](https://hstspreload.org/) and always serves the headers:
````nginx configuration pro
add_header Expect-CT                 "max-age=86400, enforce"                       always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
````

* Additionally, the entire zone is dual-signed with **DNSSEC**. See the current **DNSSEC** status at: **[DNSSEC Audit Report](/docs/AUDIT_DNSSEC.md)**
* A comprehensive TLS audit of the **`git.coresecret.dev`** Gitea server is also available. See: **[TLS Audit Report](/docs/AUDIT_TLS.md)**
* The infrastructure of the **`CISS.debian.live.builder`** building system is visualized here. See: **[Centurion Net](/docs/CNET.md)**

### 1.1.3. Gitea Action Runner Hardening

The CI runners operate on a dedicated host system located in a completely separate Autonomous System (AS). This host is solely 
dedicated to providing CI runners and does not perform any other tasks. Each runner is hermetically isolated from others using 
non-privileged, shell-less user accounts with no direct login capability. Additionally, each runner executes within its own 
separate directory tree, employs `DynamicUser` features, and adheres to strict systemd hardening policies (achieving a ``systemd-analyze security`` 
rating of **``2.6``**). Docker containers used by runners do not run in privileged mode. Security is further enhanced through the use 
of both UFW software firewalls and dedicated hardware firewall appliances.

## 1.2. Match Host and Target Versions

Build, for example, a Debian Trixie live image only on a Debian Trixie host. The build toolchain and boot artifacts are 
release-specific: ``live-build``, ``live-boot``, ``live-config``, ``debootstrap``, ``kernel/initramfs`` tools, ``mksquashfs``, 
``GRUB/ISOLINUX``, and even ``dpkg/apt`` often change defaults and formats between releases (e.g., compression modes, SquashFS 
options, hook ordering, systemd/udev behavior). Building on a different host release commonly yields non-reproducible or even 
unbootable ISOs (missing modules/firmware, ABI mismatches, divergent paths). Keeping host and target on the same version ensures
reproducible builds, matching dependencies, and compatible boot artifacts.

## 1.3. Immutable Source-of-Truth System

This live ISO establishes a secure, fully deterministic, integrity self-verifying boot environment based entirely on static
source-code definitions. All configurations, system components, and installation routines are embedded during build time and 
locked for runtime immutability. This ensures that the live environment functions as a trusted **Source of Truth** — not only 
for boot-time operations, but for deploying entire systems in a secure and reproducible way.<br>

Once booted, the environment optionally launches a fully scripted installer, via the forthcoming `CISS.debian.installer`,
yet to deploy, that provisions the target system (the hardware the DVD is running on). The installer pulls no external 
dependencies besides of the necessary Debian debootstrap and Debian Packages and never exposes the target system in a not 
secure manner to the internet during installation. It operates strictly from within the verified image content, providing fully 
secured provisioning. Combined with checksum verification, **activated by default**, at boot and strict firewall defaults, this 
architecture guarantees that what is executed has not been tampered with and corresponds exactly to the intended source definition.<br>

An even more secure deployment variant — an unattended and headless version — can be built without any active network interface
or shell-access, also via the forthcoming `CISS.debian.installer`. Such a version performs all verification steps autonomously, 
provisions the target device from embedded source artifacts, and reboots into a fully encrypted system image. The system then 
awaits the decryption passphrase input via an embedded Dropbear SSH server (SSH PubKey only) in the initramfs, exposing no ports
without cryptographic hardened access, while also the `/boot` partition could be encrypted via the built-in support of 
`grub2 (2.12-9)`.<br>

This approach provides a fully reproducible, audit-friendly, and tamper-resistant provisioning workflow rooted entirely in 
source-defined infrastructure logic.<br>

After build and configuration, the following audit reports can be generated:

* **Haveged Audit Report**: Validates entropy daemon health and confirms `/dev/random` seeding performance.
  Type `chkhvg` at the prompt. See example report: **[Haveged Audit Report](/docs/AUDIT_HAVEGED.md)**
* **Lynis Audit Report**: Outputs a detailed security score and recommendations, confirming a 91%+ hardening baseline.
  Type `lsadt` at the prompt. See example report: **[Lynis Audit Report](/docs/AUDIT_LYNIS.md)**
* **SSH Audit Report**: Verifies SSH daemon configuration against the latest best-practice cipher, KEX, and MAC recommendations.
  Type `ssh-audit <IP>:<PORT>`. See example report: **[SSH Audit Report](/docs/AUDIT_SSH.md)**

## 1.4. Preview

![CISS.debian.live.builder](/docs/screenshots/CISS.debian.live.builder_preview.jpeg)

## 1.5. Caution. Significant information for those considering using D-I.

**The Debian Installer (d-i) will ALWAYS boot a new system.**<br>

Regardless of whether you start it:
* via the boot menu of your Live ISO (grub, isolinux) like **CISS.debian.live.builder**,
* via kexec in the running system,
* via the debian-installer-launcher package,
* or even via a graphical installer shortcut.

The following happens in all cases:
* The installer kernel (/install/vmlinuz) + initrd.gz are started.
* The existing live system is exited.
* The memory is overwritten.
* All running processes - e.g., firewall, hardened SSH access, etc. pp. - cease to exist.

The Debian Installer loads:
* its own kernel,
* its own initramfs,
* its own minimal root filesystem (BusyBox + udeb packages),
* no SSH access (unless explicitly enabled via preseed)
* no firewall, AppArmor, logging, etc. pp.,
* it disables all running network services, even if you were previously in the live system.

This means function status of the **CISS.2025.debian.live.builder** ISO after d-i start:
* ufw, iptables, nftables ✘ disabled, not loaded,
* sshd with hardening ✘ stopped (processes gone),
* the running kernel ✘ replaced,
* Logging (rsyslog, journald) ✘ not active,
* preseed control over the network is possible (but without any protection).

## 1.6. Versioning Schema

This project adheres strictly to a structured versioning scheme following the pattern x.y.z-Date.

Example: `V8.13.272.2025.10.22`

`x.y.z` represents major (x), minor (y), and patch (z) version increments.

Date (YYYY.MM.DD) denotes the build or release date, facilitating clear tracking of incremental changes and ensuring 
reproducibility and traceability.

## 1.7. Keywords

The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED",
"MAY", and "OPTIONAL" in this Repo are to be interpreted as described in [[BCP 14](https://www.rfc-editor.org/info/bcp14)], 
[[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)], [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when,
and only when, they appear in all capitals, as shown here.

# 2. Features & Rationale

Below is a breakdown of each hardening component, with a summary of why each is critical to your security posture.

## 2.1. Kernel Hardening

### 2.1.1. Boot Parameters

* **Description**: Customizes kernel command-line flags to disable unused features and enable mitigations.
* **Key Parameters**:
  * `audit_backlog_limit=8192`: Ensures the audit subsystem can queue up to 8192 events to avoid dropped logs under heavy loads.
  * `audit=1`: Enables kernel auditing from boot to record system calls and security events.
  * `cfi=kcfi`: Activates kernel control-flow integrity using kCFI to protect against control-flow hijacking.
  * `debugfs=off`: Disables debugfs to prevent non-privileged access to kernel internals.
  * `efi=disable_early_pci_dma`: Stops early PCI DMA under EFI to mitigate DMA-based attacks during boot.
  * `efi_no_storage_paranoia`: Disables extra EFI storage checks to streamline boot without compromising expected storage integrity.
  * `hardened_usercopy=1`: Enables stringent checks on copy operations between user and kernel space to prevent buffer overflows.
  * `ia32_emulation=0`: Turns off 32-bit compatibility modes to reduce attack surface on 64-bit hosts.
  * `init_on_alloc=1`: Zeroes memory on allocation to prevent leakage of previous data.
  * `init_on_free=1`: Initializes memory on free to catch use-after-free bugs.
  * `iommu=force`: Enforces IOMMU for all devices to isolate DMA-capable hardware.
  * `kfence.sample_interval=100`: Configures the kernel fence memory safety tool to sample every 100 allocations.
  * `kvm.nx_huge_pages=force`: Enforces non-executable huge pages in KVM to mitigate code injection.
  * `l1d_flush=on`: Flushes L1 data cache on context switch to mitigate L1D vulnerabilities.
  * `lockdown=confidentiality`: Puts the kernel in confidentiality lockdown to restrict direct hardware access.
  * `loglevel=0`: Suppresses non-critical kernel messages to reduce information leakage.
  * `mce=0`: Disables machine check exceptions to prevent side-channel data leaks from hardware error reporting.
  * `mitigations=auto,nosmt`: Enables all automatic CPU mitigations and disables SMT to reduce side-channel risks.
  * `mmio_stale_data=full,nosmt`: Ensures stale MMIO data is fully flushed and disables SMT for added protection.
  * `oops=panic`: Forces a kernel oops to trigger a panic, preventing the system from running in an inconsistent state.
  * `page_alloc.shuffle=1`: Randomizes physical page allocation to hinder memory layout prediction attacks.
  * `page_poison=1`: Fills freed pages with a poison pattern to detect use-after-free.
  * `panic=-1`: Disables automatic reboot on panic to preserve the system state for forensic analysis.
  * `pti=on`: Enables page table isolation to mitigate Meltdown attacks.
  * `random.trust_bootloader=off`: Prevents trusting entropy provided by the bootloader.
  * `random.trust_cpu=off`: Disables trusting CPU-provided randomness, enforcing external entropy sources.
  * `randomize_kstack_offset=on`: Randomizes the kernel stack offset on each syscall entry to harden against stack probing.
  * `randomize_va_space=2`: Enables full address space layout randomization (ASLR) for user space.
  * `retbleed=auto,nosmt`: Enables automatic RETBLEED mitigations and disables SMT for better side-channel resistance.
  * `rodata=on`: Marks kernel read-only data sections to prevent runtime modification.
  * `tsx=off`: Disables Intel TSX extensions to eliminate related speculative execution vulnerabilities.
  * `vdso32=0`: Disables 32-bit vDSO to prevent unintended cross-mode calls.
  * `vsyscall=none`: Disables legacy vsyscall support to close a potential attack vector.
* **Rationale**: Ensures early activation of protections, reducing exposure to CPU vulnerabilities before the system fully boots.

### 2.1.2. CPU Vulnerability Mitigations

* **Description**: Enables all known kernel-level mitigations (Spectre, Meltdown, MDS, L1TF, etc.).
* **Rationale**: Prevents side-channel attacks that exploit speculative execution, which remain a high-risk vector in
  multi-tenant cloud environments.

### 2.1.3. Kernel Self-Protection

* **Description**: Activates `CONFIG_DEBUG_RODATA`, `CONFIG_STRICT_MODULE_RWX`, and other self-protections.
* **Rationale**: Hardens kernel memory regions against unauthorized writings and enforces stricter module loading policies.

### 2.1.4. Local Kernel Hardening

* **Description**: The wrapper `sysp()`provides a function to apply and audit local kernel hardening rules from `/etc/sysctl.d/99_local.hardened`:
````bash
###########################################################################################
# Globals: Wrapper for loading CISS.2025 hardened Kernel Parameters
# Arguments:
#  none
###########################################################################################
# shellcheck disable=SC2317
sysp() {
  sysctl -p /etc/sysctl.d/99_local.hardened
  # sleep 1
  sysctl -a | grep -E 'kernel|vm|net' > /var/log/sysctl_check"$(date +"%Y-%m-%d_%H:%M:%S")".log
}
````
* **Key measures loaded by this file include:**
  * Disabling module loading `kernel.modules_disabled=1`
  * Restricting kernel pointers & logs `kernel.kptr_restrict=2`, `kernel.dmesg_restrict=1`, `kernel.printk=3 3 3 3`
  * Disabling unprivileged BPF and userfaultfd
  * Disabling kexec and unprivileged user namespaces
  * Locking down ptrace scope `kernel.yama.ptrace_scope=2`
  * Protecting filesystem links and FIFOs `fs.protected_*`

**Warning**
Once applied, some hardening settings cannot be undone via `sysctl` without a reboot, and dynamic module loading remains disabled
until the next boot. Automatic enforcement at startup is therefore omitted by design—run `sysp()` manually and plan a reboot to 
apply or revert these controls.

## 2.2. Module Blacklisting

* **Description**: Disables and blacklists non-essential or insecure kernel modules.
* **Rationale**: Minimizes attack surface by preventing loads of drivers or modules not required by the live environment.

## 2.3. Network Hardening

* **Description**: Applies `sysctl` settings (e.g., `net.ipv4.conf.all.rp_filter=1`, `arp_ignore`, `arp_announce`) to restrict
  inbound/outbound traffic behaviors.
* **Rationale**: Mitigates ARP spoofing, IP spoofing, and reduces the risk of man-in-the-middle on internal networks.

## 2.4. Core Dump & Kernel Hardening

* **Description**: Limits core dump generation paths, enforces `Yama` restrictions, and configures `kernel.kptr_restrict`.
* **Rationale**: Prevents leakage of sensitive memory contents and reduces information disclosure from unintentional crash
  dumps.

## 2.5. Entropy Collection Improvements

* **Description**: Installs and configures `haveged`, seeds `/dev/random` early.
* **Rationale**: Cloud instances frequently suffer low entropy at the start; improving randomness ensures strong cryptographic key
  generation for SSH and other services.

## 2.6. Permissions & Authentication

* **Description**: Sets strict directory and file permissions, integrates with PAM modules (e.g., `pam_faillock`).
* **Rationale**: Enforces the principle of least privilege at file-system level and strengthens authentication policies.

## 2.7. High-Security Baseline (Lynis Audit)

* **Description**: Run a baseline audit via [Lynis](https://cisofy.com/lynis/) after build completion. 
  The generated live environment consistently achieves a 91%+ score in Lynis security audits.
* **Rationale**: Provides independent verification of security posture and flags any configuration drifts or missing
  hardening steps.

## 2.8. SSH Tunnel & Access Security

* **Description**: The SSH tunnel and access are secured through multiple layers of defense:
  * **Firewall Restriction**: ufw allows connections only from defined jump host or VPN exit node IPs.
  * **TCP Wrappers**: `/etc/hosts.allow` and `/etc/hosts.deny` enforce an `ALL: ALL` deny policy, permitting only specified hosts.
  * **One-Hit Ban**: A custom Fail2Ban rule `/etc/fail2ban/jail.d/ciss-default.conf` immediately bans any host 
    that touches closed ports. 
    * Additionally, the `fail2ban` service is hardened as well according to:
    [Arch Linux Wiki Fail2ban Hardening](https://wiki.archlinux.org/title/fail2ban#Service_hardening) 
  * **SSH Ultra-Hardening**: The `/etc/sshd_config` enforces strict cryptographic and connection controls with respect to 
    [SSH Audit Guide Debian 12](https://www.ssh-audit.com/hardening_guides.html#debian_12):
    * `RekeyLimit 1G 1h`
    * `HostKey /etc/ssh/ssh_host_ed25519_key`
    * `HostKey /etc/ssh/ssh_host_rsa_key (8192-bit RSA)`
    * `PubkeyAuthentication yes`
    * `PermitRootLogin prohibit-password`
    * `PasswordAuthentication no`
    * `PermitEmptyPasswords no`
    * `LoginGraceTime 2m`
    * `MaxAuthTries 3`
    * `MaxSessions 2`
    * `MaxStartups 08:64:16`
    * `PerSourceMaxStartups 4`
    * `RequiredRSASize 4096`
    * `Ciphers aes256-gcm@openssh.com`
    * `KexAlgorithms sntrup761x25519-sha512@openssh.com,sntrup761x25519-sha512,gss-curve25519-sha256-`
    * `MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com`
* **Rationale**: These measures ensure that only authorized hosts can establish SSH tunnels, with strict cryptographic and usage 
  policies enforced. Minimizes brute force, passive sniffing, and reduces credentials' exposure by limiting protocol features to
  vetted algorithms.

## 2.9. UFW Hardening

* **Description**: Defaults to `deny incoming` and (optionally) `deny outgoing`; automatically opens only whitelisted ports.
* **Rationale**: Implements a default-deny firewall, reducing lateral movement and data exfiltration risks immediately after
  deployment.

## 2.10. Fail2Ban Enhancements

* **Description**:
  * Bans any connection to a closed port for 24 hours
  * Automatically ignores designated bastion/jump host subnets
  * Hardened via `systemd` policy override to limit privileges of the Fail2Ban service itself
* **Rationale**: Provides proactive defense against port scans and brute-force attacks, while isolating the ban daemon in a
  minimal-privilege context.

## 2.11. NTPsec & Chrony

* **Description**: Installs `chrony`, selects PTB NTPsec servers by default.
* **Rationale**: Ensures tamper-resistant time synchronization, which is essential for log integrity, certificate validation,
  and forensic accuracy.

# 3. Script Features & Rationale

## 3.1. Input Validation & Security

* **Description**: All script arguments are validated using a robust input sanitizer.
* **Rationale**: Prevents injection attacks and ensures only expected data types and values are processed.

## 3.2. Debug Mode with Detailed Logging

* **Description**: A built-in debug mode outputs clear, timestamped logs including:

  * Script Name and Path of called Function,
  * Line Number,
  * Function Name,
  * Exit Code of the previous Command,
  * Executed Command.
* **Rationale**: Simplifies troubleshooting and provides precise error tracing.

## 3.3. Secure Debug Logging

* **Description**: No hardcoded plaintext password fragments or sensitive artifacts appear in debug logs.
* **Rationale**: Prevents accidental exposure of credentials during troubleshooting.

## 3.4. Secure Password Handling

* **Description**: Password files, if provided, are shredded immediately after being hashed.
* **Rationale**: Prevents password recovery from temporary files.

## 3.5. Variable Declaration & Validation

* **Description**: All variables are declared and validated before use.
* **Rationale**: Avoids unintended behavior from unset or improperly set variables.

## 3.6. Pure Bash Implementation

* **Description**: The entire wrapper and all its functions are written in pure Bash, without external dependencies.
* **Rationale**: Ensures maximum portability and compatibility with standard Debian environments.

## 3.7. Bash Error Handling

* **Description**: The implemented xtrace wrapper `set -x` enforces comprehensive Bash error handling to ensure
  * robust, 
  * predictable execution,
  * and early detection of failures.
  
  and delivers full information, which command failed to execute:
  * Script Name and Path of called Function,
  * Line Number,
  * Function Name,
  * Exit Code of the previous Command,
  * Executed Command,
  * Environment Settings,
  * Argument Counter passed to Script,
  * Argument String passed to Script.

* The following `set` options are applied at the beginning of the script (see 
  [Bash Manual, The Set Builtin](https://www.gnu.org/software/bash/manual/bash.html#The-Set-BuiltinGNU)):
```bash
set -o errexit   # Exit script when a command exits with non-zero status (same as "set -e").
set -o errtrace  # Inherit ERR traps in subshells (same as "set -E").
set -o functrace # Inherit DEBUG and RETURN traps in subshells (same as "set -T").
set -o ignoreeof # An interactive shell will not exit upon reading EOF.
set -o nounset   # Exit script on use of an undefined variable (same as "set -u").
set -o pipefail  # Return the exit status of the last failed command in a pipeline.
set -o noclobber # Prevent overwriting files via redirection (same as "set -C").
```

* The following `shopt` options are applied at the beginning of the script (see
  [Bash Manual, The Shopt Builtin](https://www.gnu.org/software/bash/manual/bash.html#The-Shopt-Builtin)):
````bash
shopt -s failglob        # If set, patterns that fail to match filenames during filename expansion result in an expansion error.
shopt -s inherit_errexit # If set, command substitution inherits the value of the errexit option instead of unsetting it in the
                         # subshell environment.
shopt -s lastpipe        # If set, and job control is not active, the shell runs the last command of a pipeline not executed in
                         # the background in the current shell environment.
shopt -u expand_aliases  # If set, aliases are expanded as described. This option is enabled by default for interactive shells.
shopt -u dotglob         # If set, Bash includes filenames beginning with a '.' in the results of filename expansion.
shopt -u extglob         # If set, enable the extended pattern matching features.
shopt -u nullglob        # If set, filename expansion patterns that match no files expand to nothing and are removed.
````

* **Rationale**: These options enforce strict error checking and handling, reducing silent failures and ensuring 
predictable script behavior.

# 4. Prerequisites

* **Host**: Debian Trixie with `live-build` and ``debootstrap`` packages installed.
* **Privileges**: Root or sudo access to execute `ciss_live_builder.sh` and related scripts.
* **Network**: Outbound access to Debian repositories and PTB NTPsec pool.

# 5. Installation & Usage

## 5.1. Interactive CLI / Dialog Wrapper

1. Clone the repository:
   ```bash
   git clone https://git.coresecret.dev/msw/CISS.debian.live.builder.git
   cd CISS.debian.live.builder
   ```
   
2. Preparation:
   1. Ensure you are root.
   2. Create the build directory `mkdir /opt/livebuild`.
   3. Place your desired SSH public key in the `authorized_keys` file, for example, in the `/opt/gitea/CISS.debian.live.builder` directory.
   4. Place your desired Password in the `password.txt` file, for example, in the `/opt/gitea/CISS.debian.live.builder` directory.
   5. Make any other changes you need to.

3. Run the config builder script `./ciss_live_builder.sh` and the integrated `lb build` command (example):

   ````bash
   chmod 0700 ./ciss_live_builder.sh
   timestamp=$(date -u +%Y-%m-%dT%H:%M:%S%z)
   ./ciss_live_builder.sh --architecture amd64 \
                          --build-directory /opt/livebuild \
                          --change-splash hexagon \
                          --control "${timestamp}" \
                          --cdi \
                          --debug \
                          --dhcp-centurion \
                          --jump-host 10.0.0.128 [c0de:4711:0815:4242::1] [2abc:4711:0815:4242::1]/64 \
                          --provider-netcup-ipv6 [c0de:4711:0815:4242::ffff] \
                          --renice-priority "-19" \
                          --reionice-priority 1 2 \
                          --root-password-file /opt/gitea/CISS.debian.live.builder/password.txt \
                          --ssh-port 4242 \
                          --ssh-pubkey /opt/gitea/CISS.debian.live.builder \
                          --trixie
   ````

4. Locate your ISO in the `--build-directory`.
5. Boot from the ISO and login to the live image via the console, or the multi-layer secured **coresecret** SSH tunnel.
6. Type `sysp` for the final kernel hardening features.
7. Check the boot log with `jboot` and via `ssf` that all services are up.
8. Finally, audit your environment with `lsadt` for a comprehensive Lynis audit.
9. Type `celp` for some shortcuts.

## 5.2. Make Wrapper, Quick Usage

This repo ships a thin make wrapper around ``./ciss_live_builder.sh``, so you can compose a correctly quoted command and either 
preview it or run it.

1. Clone the repository:

   ```bash
   git clone https://git.coresecret.dev/msw/CISS.debian.live.builder.git
   cd CISS.debian.live.builder
   ```

2. Preparation:
   1. Ensure you are root.
   2. Create the build directory `mkdir /opt/livebuild`.
   3. Place your desired SSH public key in the `authorized_keys` file, for example, in the `/opt/gitea/CISS.debian.live.builder` directory.
   4. Place your desired Password in the `password.txt` file, for example, in the `/opt/gitea/CISS.debian.live.builder` directory.
   5. Copy and edit the sample and set your options (no spaces around commas in lists): 

    ````bash
    cp config.mk.sample config.mk
    ````

    ````bash
    BUILD_DIR=/opt/livebuild
    ROOT_PASSWORD_FILE=/opt/gitea/CISS.debian.live.builder/password.txt
    SSH_PORT=4242
    SSH_PUBKEY=/root/.ssh

    # Optional
    PROVIDER_NETCUP_IPV6=2001:cdb::1
    # comma-separated; IPv6 in [] is fine
    JUMP_HOSTS=[2001:db8::1],[2001:db8::2]     
    ````

3. Dry-run first (prints the exact command): ````make dry-run````

4. Execute the build: ````make live````

## 5.3. CI/CD Gitea Runner Workflow Example

1. Clone the repository:

   ```bash
   git clone https://git.coresecret.dev/msw/CISS.debian.live.builder.git
   cd CISS.debian.live.builder
   ```
2. Edit the `.gitea/workflows/generate-iso.yaml` file according to your requirements. Ensure that the trigger file
   `.gitea/trigger/t_generate.iso.yaml` and the counter are updated. Change all the necessary `{{ secrets.VAR }}`.
   Push your commits to trigger the workflow. Then download your final ISO from the specified Location.

  ```yaml
  #...
      steps:
        - name: Preparing SSH Setup, SSH Deploy Key, Known Hosts, .config.
          run: |
            rm -rf ~/.ssh && mkdir -m700 ~/.ssh

            ### Private Key
            echo "${{ secrets.CHANGE_ME }}" >| ~/.ssh/id_ed25519
            chmod 600 ~/.ssh/id_ed25519
  #...
        ### https://github.com/actions/checkout/issues/1843
        - name: Using manual clone via SSH to circumvent Gitea SHA-256 object issues.
          run: |
            git clone --branch "${GITHUB_REF_NAME}" ssh://git@CHANGE_ME .
  #...
        - name: Importing the 'CI PGP DEPLOY ONLY' key.
          run: |
            ### GPG-Home relative to the Runner Workspace to avoid changing global files.
            export GNUPGHOME="$(pwd)/.gnupg"
            mkdir -m700 "${GNUPGHOME}"
            echo "${{ secrets.CHANGE_ME }}" >| ci-bot.sec.asc
  #...
        - name: Configuring Git for signed CI/DEPLOY commits.
          run: |
            export GNUPGHOME="$(pwd)/.gnupg"
            git config user.name "CHANGE_ME"
            git config user.email "CHANGE_ME"
  #...
        - name: Preparing the build environment.
          run: |
            mkdir -p /opt/config
            mkdir -p /opt/livebuild
            echo "${{ secrets.CHANGE_ME }}" >| /opt/config/password.txt
            echo "${{ secrets.CHANGE_ME }}" >| /opt/config/authorized_keys
  #...
        - name: Starting CISS.debian.live.builder. This may take a while ...
          run: |
            chmod 0700 ciss_live_builder.sh && chown root:root ciss_live_builder.sh
            timestamp=$(date -u +"%Y_%m_%d_%H_%M_Z")
            ### Change "--autobuild=" to the specific kernel version you need: '6.12.22+bpo-amd64'.
            ./ciss_live_builder.sh \
              --autobuild=CHANGE_ME \
              --architecture CHANGE_ME \
              --build-directory /opt/livebuild \
              --control "${timestamp}" \
              --jump-host "${{ secrets.CHANGE_ME }}" \
              --root-password-file /opt/config/password.txt \
              --ssh-port CHANGE_ME \
              --ssh-pubkey /opt/config
  #...
        ### SKIP OR CHANGE ALL REMAINING STEPS
  ```

# 6. Licensing & Compliance

This repository is fully SPDX-compliant. All source files include appropriate SPDX license identifiers and headers to ensure
clear and unambiguous licensing. You can verify compliance by reviewing the top of each file, which follows the SPDX
standard for license expressions and metadata.

# 7. Disclaimer

This README is provided "as-is" without any warranty. Review your organization's policies before deploying to production.

---
**[no tracking | no logging | no advertising | no profiling | no bullshit](https://coresecret.eu/)**
<!-- vim: set number et ts=2 sw=2 sts=2 ai tw=128 ft=markdown -->
