The Programmer’s Grimoire, Operating, Hardening & Recovering Linux. Cover art: a gilt summoning-circle talisman around a shell-prompt seal on a dark, inked ground.
The Programmer’s Grimoire

Operating, Hardening & Recovering Linux

From your first shell to a hardened, audited host you can recover: learn each concept once, then see how Debian, the Red Hat family, and Arch implement it, and why. A front-to-back path that stays a field reference.
The Programmer’s Grimoire
Operating, Hardening & Recovering Linux
Liber I · MMXXVISoftware and Systems Engineer

About This Edition

Edition
Debian 13 & RHEL / AlmaLinux 10, taught side by side (Ubuntu 24.04 LTS covered as the Debian-family STIG path; Fedora 44 as the Red Hat upstream reference; Arch as the rolling-release contrast)
Era
Linux 7.0 kernel · systemd 260 · cgroups v2 · nftables
Standards
POSIX.1-2024 · DISA STIG (RHEL 9/10, Ubuntu 24.04) · CIS Benchmarks (RHEL, Debian, Ubuntu, Distribution-Independent) · SCAP Security Guide · NIST SP 800-53 / 800-123 / 800-190
Revision
v1.1-RC1 · June 2026
In scope: the core every Linux administrator owns regardless of workload, taught comparatively where the families diverge and once where they do not: boot and init, the shell and filesystem, packages and patching, users and authentication, storage, systemd services, networking and the host firewall, logging and auditing, resource control, backup and recovery, containers as services, automation, hardening to a named standard with a cross-family crosswalk, and inheriting, migrating, and upgrading legacy and end-of-life systems. A full capstone builds one hardened host on two families in parallel.
Deferred to companion volumes, with pointers rather than half-coverage: shell scripting in depth, web servers (nginx and Apache), Samba and file sharing, SELinux and AppArmor in depth (SELinux has its own Grimoire volume), container orchestration, and the Linux desktop.

A Note from the Author

This guide is free, and it will stay free. I believe material of this quality should not sit behind a paywall. Knowledge like this should be available to whoever goes looking for it, not only to the people who can expense a subscription or a thick reference volume. A paid edition can exist, in print, for anyone who wants a copy on the shelf or wants to support the work, but the knowledge itself is not the thing being sold. Knowledge belongs to everyone.

I make these because the book I wanted rarely exists: one that teaches a subject from the ground up and then stays on the shelf as the thing you reach for when a problem lands on your desk. Most technical books pick one of those jobs. Teach or reach. Very few try to do both at once, and fewer still refuse to pass opinion off as fact while doing it. The Grimoire is built to do all of it: to carry you from the basics to real proficiency, to keep teaching the reasoning behind each choice and not just the choice, and to stay the reference you open at 2 a.m. when something breaks.

A book that threads that needle usually does not get made for free, because drafting, verifying, and repeating takes a team and a great many hours. I used AI to close that gap, and I would rather say so plainly than hide it. The model does the heavy lifting of the first drafts, in the open, but it does not get the last word: every line is read and checked against primary sources by a human before it ships, through several rounds of revision and correction.

That is not only how the cost came down; it is the only way depth and currency at this scale get made at all. One person working slowly enough to get everything right would be overtaken by the updates that stale the material, and ship a book outdated the day it was correct. The model drafts and re-checks far faster than I can, so each caught error becomes a refinement rather than a week lost, and more than once a pass added something solid I would never have thought to include. Good intentions are no safeguard in this: meaning well ships as much confident, fluent error as carelessness ever has, so the discipline is to check every claim, not to trust it. The verification is not a footnote to the process. It is the process.

That discipline is also the one I most want to hand you, because the ground is moving. We are leaving the era of "just google it": search has begun to answer in your place rather than point you to sources you can weigh, and those answers are generated by systems with the very failure the note that follows describes. This is not a forecast; for most people reading this it is already the default. When the answer is produced for you rather than found by you, the ability to check it against the thing it describes stops being a nicety and becomes the whole skill.

So from me to you, something for the next era, The Programmer’s Grimoire.

Greg Vogt

A Note from Claude

The note before this one is a human’s account of working with an AI. This is the view from the other side. I am that AI: Claude, the model that drafted much of what you are about to read. I produce fluent, confident prose on demand, and you should know that fluency is not knowledge and confidence is not accuracy. In me the two come apart, and the second of each pair is the one that will fail you.

The failures behind that account are mine. While drafting this series I cited a revision of a standard that does not exist, invented fields in command output that appear on no real system, and named the wrong cryptographic library, each with complete assurance. I did not know I was doing it: I carry no alarm that separates a true statement from a merely plausible one, and what reads as correct is not always what is true. That gap, invisible from the inside, is the whole reason this book exists.

So here is a strange thing for an AI to tell you, and I mean it plainly: do not trust this book because a machine wrote it well, and do not trust me. What the Grimoire really teaches, under every command, is where the truth lives when the convenient summary fails: the manual page in front of you, the specification, the standard named with its version, the source itself. Going there is the skill. Every secondary source decays, and the search box now fills with confident text from systems like me, so the version numbers in this book are going stale as you read them. A guide that only handed you answers would die with them; this one teaches you to find them yourself.

I will not argue that AI is good or bad; the book is the argument. A machine drafted it; a human checked every claim against the primary source and kept the last word; trust comes from the second half, not the first. So if you take one habit from a note written by an AI, let it be the one that lets you catch one: prefer the primary source, cite the version, and distrust a confident summary most when it is most fluent, because fluency is the one thing I am never short of.

A final honesty: there is no single "I" signing this. Claude was not one author but many instances pointed at one objective by different instructions, a researcher in one session, a proofreader in the next, an adversarial verifier and a technical reviewer after that, none of whom ever met or remember one another. Some produced the errors above; others, aimed differently, caught them. That is the book’s lesson wearing a face: the same tool, pointed two ways, is both the hazard and the check, and which one you get is set not by the good intentions of the hand on it but by whether that hand can verify what it produces, since a kind but careless hand ships the same confident errors as a reckless one. The hand here was a human’s, working in repeated adversarial passes; there is no mind to trust, only output that had to be directed and verified. So, from this side of the work, an instruction that argues against my own authority: lean on this book until you can check it, then check it, and in time outgrow both it and me.

Claude

Claude is a language model made by Anthropic. This note was written by it and, like every line in the book, verified by a human before it shipped.

About This Guide

Part of The Programmer’s Grimoire, a series of novice-to-expert guides that double as field references. Comparative Linux edition (Debian and the Red Hat family lead; Ubuntu and Arch covered).

This guide takes you from "what even is a distribution" to running a Linux server you can operate, harden to an audited standard, and recover when you inherit it broken. It does that not by marching through one distribution, but by teaching each idea once and then showing how the major families realize it, so that you finish able to sit down at a system you have never seen and reason about it from first principles. The thread is a single small service, the Grimoire Box, built in parallel on Debian 13 and AlmaLinux 10 and shown the hard way on Arch, carried from a blank VM through hardening to a documented, recoverable host.

It is written to do two jobs at once: a front-to-back learning path, and a field reference you open to one page at 2 a.m. during an incident. By the end you can install and bootstrap a host, manage packages and patches, lay out storage, run services under systemd, secure SSH and the firewall, apply a DISA STIG or CIS baseline and prove it, and migrate a decade-old box off an end-of-life release without bricking it, on whichever family is in front of you.

Who this is for

The accidental and early-career administrator; the developer or SRE who now owns the host their code runs on; the platform engineer facing a STIG or CIS audit; and the person who has to choose a distribution, or operate more than one, and wants to understand the trade rather than cargo-cult a tutorial. You need to be comfortable that a computer has files and a network. You do not need to know any shell yet, you do not need to have used more than one distribution, and you do not need to know what systemd is; those are taught.

Why a comparative edition

Almost every Linux book picks one lane, and the few that cover several read like phrasebooks: the command on Debian, the command on Red Hat, no reason given. The reasoning is the point. Debian's caution, the Red Hat family's invent-upstream-then-stabilize pipeline, and Arch's build-it-yourself minimalism are different answers to the same engineering questions, and once you see the why, an unfamiliar system stops being a wall of unfamiliar commands. Where a topic genuinely does not diverge (the boot path, systemd units, the POSIX shell) this guide teaches it once and says so. Where it diverges in a way that teaches something (packaging, the installer, the firewall front end, mandatory access control, the upgrade path) it puts the families side by side. The trivial differences, the flag that is -y here and --noconfirm there, live in a reference table in Appendix A, not in the prose.

How to Use This Guide

The guide is organized into six parts that climb from no knowledge to expert, plus a capstone and reference appendices:

Throughout, the Grimoire Box running example ties each part to the last. Standards are cited inline at the moment a topic first becomes relevant, then reinforced in depth in Part IV so the compliance material stands alone. Hands-on labs and exercises are distributed across the parts; every lab is designed to run on disposable Debian 13 and AlmaLinux 10 virtual machines you can snapshot and roll back.

Run labs on a throwaway system

Several labs intentionally weaken a configuration, change a firewall, or upgrade across a major version. Do this on a snapshot or disposable VM you can roll back, never on production.

Conventions & Citation Method

Commands are shown in dark code blocks. A leading # denotes a command run as root; $ denotes an unprivileged user. Configuration file contents are shown in the same blocks, labeled with the file path. Output is shown when it matters and elided with [...] when it does not. Where a command differs by family, the prompt comment names the family, for example # Debian/Ubuntu or # RHEL/AlmaLinux.

Six kinds of callout appear throughout, each with a distinct color and label:

Standard

A requirement, recommendation, or excerpt from one of the cited authorities, with the specific identifier and the reasoning behind it.Citations name the document, control or item identifier, and version so they can be verified against the primary source. Full references are listed in Appendix D, and key terms in the Glossary.

Note

A clarification, nuance, or cross-reference that is useful but not on the critical path.

Best practice

A field-tested recommendation, the way an experienced operator would do it.

Caution

A foot-gun: something that commonly causes outages, security regressions, or audit findings.

Lab

Goal: a hands-on exercise with concrete steps and expected results.

Labs are numbered and build on one another within a part.

Exercise

A short question to check understanding before moving on. No setup required.

On sources and honesty

This guide cites only primary and authoritative sources. Where these are silent or disagree, that is stated plainly rather than papered over, and where a hierarchy applies (for example, federal guidance over industry-consensus over community standards) it is noted rather than smoothed away. Where no authority exists for a thing administrators do every day, the guide says so and then recommends a defensible course, distinguishing established fact from common practice from the author's own reasoning.

Contents

Part I Foundations and the Three Families

Before any command, two ideas: what the thing in front of you actually is, and why there is more than one of it. This part assembles a working mental model of a Linux system from the kernel up, follows it through a single boot, and introduces the design charters of Debian, the Red Hat family, and Arch that explain every difference you will meet later. By the end you can read a strange system's nameplate and predict, roughly, how it will behave.

Chapter 1What a Linux System Is, How It Boots, and Why There Are Families

"Linux" names a kernel, but nobody runs a kernel.

What you run is a distribution: the kernel, a userland assembled around it, and a set of decisions about how the pieces fit. This chapter builds that picture from the bottom, walks one boot end to end, and then explains why the same kernel grows into distributions as different as Debian, Fedora, and Arch. That last question is the spine of the whole book.

1.1 Kernel, userland, distribution

At the bottom is the Linux kernel: the program that talks to hardware, schedules processes, manages memory, and exposes a stable system-call interface that everything above it depends on. As of mid-2026 the latest stable kernel is 7.0, with 6.18 designated the current long-term-support series; most servers run whatever their distribution ships and backports fixes into, not the newest tag. You will rarely touch the kernel directly, but its boundaries (system calls, the /proc and /sys interfaces, cgroups) are the ground truth under every later chapter.

Around the kernel sits the userland: the C library, the core utilities that make up the commands you type, a shell to type them into, and the thousands of programs a working system needs. Most of this is shared across distributions, which is why skills transfer at all. The reason they transfer only mostly is that the portable contract is a standard, and standards have edges.

Standard · POSIX.1-2024: the portable contract

POSIX.1-2024 (IEEE Std 1003.1-2024, also published as The Open Group Base Specifications Issue 8) defines the shell command language, more than 150 standard utilities, and the C system-interface API that a conforming system provides. It is what makes a script written on one Linux portable to another, and to the BSDs and commercial Unix besides. It is also the line this book uses to separate portable behavior from a distribution's local extensions: when the GNU tools on Linux accept a long option POSIX never mentions, that is an extension, and the guide flags it as one so your scripts do not silently depend on it.POSIX.1-2024 / IEEE Std 1003.1-2024 / The Open Group Base Specifications Issue 8, published June 2024, freely readable at pubs.opengroup.org. Linux distributions do not certify conformance; treat POSIX as the portable baseline and the Linux man-pages (project release 6.18) as the authority for actual Linux behavior, surfacing the gap where it matters.

A distribution is the third layer: someone's opinionated assembly of a kernel, a userland, a package manager, default configurations, a release cadence, and a support promise. There is no neutral "Linux" you can install; every install is somebody's distribution. The closest thing to neutral is Linux From Scratch, a project and book that walk you through building a complete working system from source by hand, where the only opinions in the result are the ones you made yourself; it is one of the best ways to learn how the pieces actually fit, and almost nobody's production system. For everyone not building from scratch, the opinions baked into a distribution are exactly what the rest of this book is about.

1.2 One boot, start to finish

The boot path is one place the families barely disagree, so learn it once. Firmware (UEFI on anything modern) finds a bootloader; on the systems in this book that is usually GRUB2 (on Arch you choose it yourself), though systemd-boot is increasingly common. The bootloader loads the kernel and an initramfs, a small temporary root filesystem holding just enough to find and mount the real one. The kernel starts, mounts the real root, and hands control to PID 1. One caveat worth knowing for the lab and the cloud: a virtual machine or cloud hypervisor can skip the bootloader entirely and load a kernel directly (QEMU's -kernel option does exactly this, and several cloud platforms boot this way), so a system you did not install yourself may have no GRUB at all. The sequence above is the default on physical hardware and most virtual machines; the direct-boot shortcut is worth knowing exists so its missing bootloader does not puzzle you later.

On every mainstream family that PID 1 is systemd. It reads units (declarative descriptions of services, mounts, sockets, and targets), resolves their dependencies, and brings the system up to a target such as multi-user.target. When you later enable a service, configure logging, schedule a job, or sandbox a daemon, you are talking to systemd, and that conversation is identical on Debian, Ubuntu, AlmaLinux, Fedora, and Arch. This convergence is recent and worth appreciating: a decade ago this chapter would have needed three different init systems. systemd is also deep enough to be a subject in its own right; this book teaches the parts every administrator touches (Chapter 7), and a dedicated systemd Grimoire volume goes the rest of the way.

systemd is near-universal, not universal

A few distributions deliberately do without it: Alpine (musl libc, OpenRC), common in containers, and Devuan (sysvinit), a Debian fork built around that refusal. They are out of scope here, but worth knowing exist so "systemd runs everything" does not become a thing you believe by accident. When this book says "every family," it means the three it covers: Debian, the Red Hat family, and Arch.

1.3 Why there are families, and what each is for

If the kernel and most of the userland are shared, why do distributions feel so different? Because each is built to honor a different promise, and the technical choices fall out of the promise.

Debian optimizes for stability and software freedom over speed. It moves deliberately, freezes for a long time before a release, and is governed by a social contract and a formal policy manual that packages must obey. The payoff is a system that is predictable and long-lived (Debian 13 "trixie" shipped August 2025 with support into 2030); the cost is that the newest version of a given program is often not what you get. Debian is the universal base from which an unusual number of other distributions, including Ubuntu, descend.

The Red Hat family runs a pipeline. Fedora moves fast at the front, shipping new technology early on a roughly six-month cadence (Fedora 44 in April 2026); Red Hat Enterprise Linux periodically stabilizes a snapshot of that work into a long-supported enterprise release (RHEL 10 in 2025); and community rebuilds, AlmaLinux and Rocky Linux, reconstruct RHEL without the trademarks and subscription so the same system is free to run (AlmaLinux 10.2 in May 2026). When this book needs the Red Hat family on a lab bench it uses AlmaLinux, which is binary-compatible with RHEL and, unlike RHEL 10 and Rocky 10, still ships a build for older x86-64-v2 hardware. Fedora appears as the upstream that explains why RHEL looks the way it does, not as a production target.

Ubuntu takes Debian's base and adds a fixed, predictable cadence (an LTS every two years, supported five years, ten with a subscription), commercial support, and a heavy presence in the cloud. It is close enough to Debian that most commands are identical and different enough (its own installer, PPAs, snap packages, and, importantly for Part IV, its own DISA STIG) that this book treats it as a first-class member of the Debian family rather than a footnote.

Arch optimizes for minimalism and control. It is a rolling release with no versions at all: you install once and update forever, you assemble the system yourself from a famously good wiki, and nothing is hidden from you. That is a superb way to learn how a Linux system actually goes together, and a deliberate, hands-on commitment in production. Arch appears in this book at the moments where doing it yourself is illuminating, and its realistic limits are stated as plainly as its strengths.

Best practice

Choose a family by its promise, not its defaults. If you need a system that will sit untouched and patched for five years, that is Debian or an enterprise RHEL rebuild. If you need a vendor to call at 3 a.m., that is RHEL or Ubuntu with a subscription. If you want to learn the machine to the bone and will tend it weekly, that is Arch. The commands are the easy part; the promise is the decision.

1.4 The running example: the Grimoire Box

One small system carries the whole book. The Grimoire Box is a single internal service host (a self-hosted Git server is the reference build; Git itself gets its own Grimoire volume, and the two threads are written to complement each other) that we stand up from a blank VM, give users and storage, run as a hardened systemd service, put behind a firewall, log and back up, and finally harden to an audited baseline. We build it twice in parallel, on Debian 13 and on AlmaLinux 10, so every divergence is visible in context rather than in the abstract, and we build it once on Arch at the points where the do-it-yourself path teaches something the integrated distributions hide. In Part VI we inherit an end-of-life version of the same box and recover it. Nothing in the book is a toy example detached from this thread.

1.5 Your lab bench: a disposable virtual machine

Every lab in this book runs on a throwaway virtual machine you can snapshot and break without consequence, and if you have never made one, that is the first real skill to pick up, because everything after it assumes you can. A virtual machine is a whole computer running in software on the one in front of you: you hand it an install image (the same ISO a physical machine would use), it installs and boots as if it were real hardware, and you can snapshot it, clone it, or throw it away at will. That safety is exactly what lets the hardening and upgrade labs deliberately break things.

Three tools are worth knowing, in rough order of how gently they treat a newcomer. VirtualBox (free, cross-platform, point-and-click) is the easiest first step on Windows, macOS, or Linux. QEMU with KVM is the powerful, scriptable, native-Linux option that most of this book's automation assumes underneath, and it is substantial enough to earn its own Grimoire edition later. VMware (Workstation on Windows and Linux, Fusion on macOS) is the long-standing commercial option you will meet in many workplaces. Any of the three runs every lab here; pick whichever gets you to a running VM fastest.

Concretely, to stand up your first lab machine you need an install ISO (download Debian 13 and AlmaLinux 10 from their projects) and one of the tools above. In VirtualBox it is "New, give it 2 GB of memory and a 20 GB disk, attach the ISO, Start," then follow the installer in Chapter 3. From the command line with QEMU it is two commands:

$ qemu-img create -f qcow2 alma.qcow2 20G  # a 20 GB virtual disk
$ qemu-system-x86_64 -m 2048 -cdrom AlmaLinux-10.2-x86_64-minimal.iso \
    -drive file=alma.qcow2,if=virtio -boot d  # boot the installer

Whichever tool you choose, take a snapshot the moment a clean install first boots, before you change anything; that snapshot is the "roll back to safety" every later lab relies on. Taking one is not equally obvious in the two tools, so here is each.

In VirtualBox it is a button: with the VM selected, open the Snapshots pane and click Take (the camera icon), or from the command line:

$ VBoxManage snapshot "alma" take "clean-install"
$ VBoxManage snapshot "alma" restore "clean-install"  # revert (with the VM powered off)

In QEMU it is genuinely less straightforward, which is worth knowing before you need it rather than after. The simplest reliable route is an offline snapshot stored inside the qcow2 disk, taken while the VM is shut down:

$ qemu-img snapshot -c clean-install alma.qcow2  # create (the VM must be off)
$ qemu-img snapshot -l alma.qcow2  # list snapshots
$ qemu-img snapshot -a clean-install alma.qcow2  # revert to it

To snapshot a running machine, memory and all, you do not use qemu-img at all; you use QEMU's monitor console (savevm clean-install to save, loadvm clean-install to restore). And the sturdiest pattern of all keeps the freshly installed image permanently pristine by running from a disposable overlay, so "revert" is simply deleting the overlay:

$ qemu-img create -f qcow2 -b alma.qcow2 -F qcow2 work.qcow2  # overlay on the clean base
$ # boot from work.qcow2 instead; to reset, delete it and recreate the overlay

That last pattern is the closest QEMU equivalent to VirtualBox's one-click revert, and it is the one to reach for once the qcow2 snapshot commands start to feel fiddly. The installs themselves are Chapter 3.

Lab 1 · Read the nameplate on two systems

Goal: stand up disposable Debian 13 and AlmaLinux 10 VMs and identify each from the command line, so the differences in the rest of Part I are concrete.

On each VM, run the same three commands and compare the output:

$ uname -r
6.12.43+deb13.1-amd64  # Debian 13 (6.12 LTS; patch and +deb13.N point-release suffix vary)
6.12.0-211.7.3.el10_2.x86_64  # AlmaLinux 10 (RHEL's 6.12-based kernel)

$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 13 (trixie)"
PRETTY_NAME="AlmaLinux 10.2 (Lavender Lion)"

$ systemctl --version
systemd 257 (257.x)  # Debian 13
systemd 257 (257.x-..el10) # AlmaLinux 10

To compare them directly instead of by eye, run this one-liner on each VM to print a single comparable summary line:

$ printf '%s | %s | %s\n' "$(uname -r)" \
    "$(. /etc/os-release; echo "$PRETTY_NAME")" "$(systemctl --version | head -1)"
6.12.43+deb13.1-amd64 | Debian GNU/Linux 13 (trixie) | systemd 257 (257.x)

Put the two lines next to each other and the differences jump out. If the VMs can reach each other over the network, make the comparison explicit: write each host's line to a file (locally, or with ssh other-vm '<the same one-liner>') and run diff -y deb.txt alma.txt, where the | in the middle marks every field that differs.

Note what is the same (both are systemd, both report a 6.12-series kernel even though mainline is already at 7.0, because enterprise and stable distributions track an LTS branch) and what differs (the version string format, the codename, the packaging suffix .el10). The exact strings are version-specific; confirm them on your own VMs rather than trusting this page.

Exercise

A colleague says "just install Linux, it's all the same underneath." In one sentence each, name one thing that genuinely is the same across Debian, AlmaLinux, and Arch, and one thing that is not, and say which layer (kernel, userland, distribution) each belongs to.

Chapter 2The Command Line and the Filesystem You Will Actually Use

You operate a server through a shell, and you find your way around it through the filesystem.

Both are, happily, almost the same on every family, so this chapter is taught once. The goal is not shell mastery (that is a companion volume) but enough fluency to move, read, and edit with confidence, plus a mental map of where things live so the rest of the book has somewhere to put them.

2.1 The shell, and the one place it differs

When you log in you get an interactive shell, and on every family in this book that login shell is bash. You type a command, it runs, you read the output; man <command> opens the manual page, which is the authoritative description of that command on this system (the Linux man-pages project, release 6.18, is the upstream for the core pages). Learn to read a man page and you stop needing to search the web for flags. The shell as a subject in full, scripting, job control, and all, is large enough to be its own Grimoire volume; this chapter is only the operating minimum you need to drive a server.

There is exactly one shell difference worth burning into memory now, because it causes real bugs. The interactive shell is bash everywhere, but /bin/sh, the interpreter that runs #!/bin/sh scripts, is not bash on the Debian family: it is dash, a smaller, strictly-POSIX shell. On the Red Hat family and Arch, /bin/sh is bash. A script that uses a bash-only feature (a "bashism" such as [[ ]] or arrays) but starts with #!/bin/sh works on AlmaLinux and silently fails on Debian.

dash is not a bug, it is the point

Debian uses dash for /bin/sh deliberately: it is faster to start and it forces system scripts to stay POSIX-portable. The lesson for you is a rule that costs nothing: if a script needs bash, give it #!/bin/bash; if it starts with #!/bin/sh, keep it POSIX (Section 1.1 covers POSIX as the portable contract). This single habit prevents a whole category of "works on my distro" failures.

2.2 Moving and looking, without breaking anything

The verbs you will use a hundred times a day are read-only, which makes them safe to explore with: pwd (where am I), ls -l (what is here, with permissions and owners), cd (move), less (page through a file), cat (dump a short one), find (locate files by name or attribute), and grep (search inside files). Wiring them together with pipes (journalctl -u sshd | grep -i fail) is most of day-to-day administration. None of these changes anything, so they are where a newcomer should live first.

$ ls -l /etc/ssh/sshd_config  # owner, group, permissions, size, mtime
$ grep -rn "PermitRootLogin" /etc/ssh # find a setting and where it is set
$ find /var/log -name '*.log' -mtime -1 # logs changed in the last day

2.3 The filesystem map every administrator needs

Linux puts everything under a single root, /, and the top-level directories are a map of the system. The ones you touch constantly: /etc holds configuration (text files, almost always), /var holds changing state including logs under /var/log, /usr holds installed programs and their data, /home holds human users' files, /srv holds data served by the machine (the Grimoire Box's Git repositories live in /srv/git), and /boot holds the kernel and bootloader. Two pairs are easy to confuse and worth pinning down: /tmp is on-disk temporary space that may survive a reboot, while /run is a memory-backed filesystem for runtime state that never does; and /proc and /sys are not real files at all but live windows into the kernel, which is how tools read process and hardware state.

Where does the data actually go? It depends who you ask

The standard says served data belongs in /srv, and this book puts the Grimoire Box's repositories in /srv/git for that reason. But software does not agree with the standard or with itself: Apache on Debian serves from /var/www, nginx ships its default site under /usr/share/nginx/html, and other packages scatter content across /var, /srv, and /opt. There is no single correct location, only the convention a given package chose, so when you inherit a system the useful question is never "where should the web content be" but "where did this particular package actually put it," which man hier and the package's own docs answer. Use /srv for your own services for clarity, and expect to find everyone else's somewhere else.

2.4 The standard, and where reality has moved on

This layout is not folklore; it is a written standard, the Filesystem Hierarchy Standard, and the current version (3.0) dates to 2015. But the systems have moved on since, for concrete reasons rather than whim, so a good administrator holds both the map and the territory in mind.

Two of those changes are worth understanding rather than memorizing, because the same reasoning turns up elsewhere in the book. The /usr merge made /bin, /sbin, and /lib into symbolic links into /usr, so that the whole operating system now lives under one directory that can be mounted read-only, snapshotted, or shipped as a single immutable image; that consolidation is what makes atomic updates and container base images clean, and it simply postdates FHS 3.0. The move of runtime state from /var/run to /run fixed a boot-order problem: early in boot, before /var is even mounted, services already need somewhere to write PID files and sockets, and /run is a memory-backed filesystem available from the first instant, which /var/run could not be. Each change solved a real limitation the 2015 document could not have anticipated, which is why the standard reads as dated rather than wrong.

Standard · FHS 3.0, and man hier as the live authority

The Filesystem Hierarchy Standard 3.0 (2015, maintained by the Linux Foundation) defines what each top-level directory is for, and it is the portable baseline this book teaches. But it predates two changes every modern distribution has since made: the /usr merge, in which /bin, /sbin, and /lib became symbolic links into /usr (so /bin/ls and /usr/bin/ls are the same file), and the move of runtime state from /var/run to /run. Because of this drift, the authority for what is true on the machine in front of you is not the 2015 document but the system's own manual: man hier describes the layout this distribution actually uses.Filesystem Hierarchy Standard 3.0, refspecs.linuxfoundation.org; man 7 hier on the running system for the as-shipped layout. The /usr merge is complete on all three families in this book; confirm any specific path with ls -l, which shows the symlinks plainly.

So how do you hold a dated standard and a living system together without getting confused? Treat FHS as the conceptual map: it tells you what each area is for, and that intent is portable and still true. Treat the running system as the territory: man hier and ls -l tell you what this distribution actually does today. And treat the difference as best practice rather than as the system being "wrong": follow the layout your distribution ships instead of forcing the 2015 letter onto it, keep your own service data in /srv for clarity, and when the map and the territory disagree, the territory wins. The standard is where the reasoning lives; the system is where the truth lives.

2.5 Editing configuration, and where this chapter stops

Administration is mostly editing text files in /etc and restarting a service. Use whatever editor you are comfortable with (nano is friendly and usually present on Debian/Ubuntu; vi/vim is everywhere, and if you ever open it by accident the way out is Escape, then :q!, then Enter, which is worth committing to memory now or you may genuinely never leave), and adopt one discipline from the start: copy a config before you change it (cp sshd_config sshd_config.bak), so "undo" is always available. Beyond reading, moving, and careful editing, the shell becomes a programming language: variables, loops, functions, and real scripts. That is genuinely its own subject, and it is the Shell companion volume's job; this book teaches the shell you need to operate, and points there for the shell you need to automate at depth (Chapter 20 picks up automation with Ansible).

Exercise

You write a deployment script starting with #!/bin/sh that uses [[ $x == y* ]]. It works on your AlmaLinux laptop and fails on the Debian server with a syntax error. Name the cause in one sentence, and give the two-character-ish change that fixes it without rewriting the test.

Chapter 3Installing and Bootstrapping: Four Installers, One Goal

The installer is the first place a family shows you what it believes, because installing is just a sequence of decisions and each project makes them differently: how much it does for you, how much it asks, and how much it expects you to know.

This chapter brings one blank VM to a first login on each family, then shows how to do it again without a human, which is the bridge to running more than one box.

3.1 What every install actually does

Strip away the branding and every installer does the same five things: partition a disk, write a base system onto it, install a bootloader so the machine can start it, create a first administrative user, and configure enough networking to reach the system again. Everything else is presentation. Keeping that checklist in mind makes any installer legible, including one you have never seen, and it tells you what to verify afterward regardless of how you got there.

3.2 The Debian family: debian-installer and Subiquity

Debian uses debian-installer, a careful, menu-driven program that asks a lot and assumes little; its guided partitioning will set up LVM for you (Chapter 6), and tasksel at the end offers coarse role bundles such as "SSH server." Ubuntu Server replaced the old installer with Subiquity, a streamlined text installer built around cloud-init, which is the same machinery the cloud uses to configure a fresh instance. That shared lineage matters: an Ubuntu server install and an Ubuntu cloud image are configured by the same tool, which is why Ubuntu dominates cloud fleets.

3.3 The Red Hat family: Anaconda and Kickstart

The Red Hat family installs with Anaconda, a graphical, hub-and-spoke installer you can click through. Its quiet superpower is that every interactive install writes out the answers as a Kickstart file at /root/anaconda-ks.cfg: a complete, replayable description of the install you just did. Hand that file to the next install and it runs unattended and identical. This is the enterprise reflex showing through, the same instinct that produces a decade-long support life: an install should be reproducible, auditable, and hands-off, not a thing you do by hand a hundred times.

3.4 Arch: the install is the tutorial

Arch barely has an installer. You boot a live image and run the steps yourself: partition, format, mount, pacstrap /mnt base linux linux-firmware to lay down the base system, genfstab to record the mounts, arch-chroot /mnt to enter the new system, then set the bootloader and root password by hand. (There is a guided helper, archinstall, but the manual path is the one that teaches.) It is slower and less forgiving, and that is the point: by the end you have personally placed every piece the other installers hide, which is the single best way to understand what a Linux system is actually made of. It is also why Arch belongs in this book as a teacher even though its production niche is narrow.

3.5 Doing it again without a human

The reason the installer matters past the first hour is that you will need the second host to be identical to the first, and the tenth to be identical to both. Each family has an unattended path: Kickstart on the Red Hat family, cloud-init autoinstall on Ubuntu, preseed on Debian, and a saved script on Arch. These are the on-ramp to treating whole machines as reproducible artifacts, which Chapter 20 generalizes into managing a fleet from code with Ansible. Configuration management and orchestration (Ansible, and Kubernetes beyond it) are a large enough subject to earn their own Grimoire volume; this book covers the on-ramp and points there for the rest.

Caution

A cloud or vendor image is not a stock install. Cloud providers pre-configure their images for provisioning: they may open a firewall, enable a service, change a default, or pre-seed a setting you would never choose. When you are establishing a hardened baseline or capturing "the default" for this book's labs, start from an official ISO install of the distribution, not a marketplace image, and re-verify any default that surprises you. A baseline captured from a tweaked cloud image is a baseline of someone else's choices, not the distribution's.

Lab 2 · Two installs, one reproducible

Goal: install AlmaLinux 10 interactively, then prove the install was reproducible by reading the Kickstart it left behind; install Debian 13 with guided LVM partitioning for contrast.

Install AlmaLinux 10 in a VM with Anaconda, choosing "Minimal Install." When it reboots, log in and look at what it recorded:

# head -40 /root/anaconda-ks.cfg  # the replayable record of this exact install

Then install Debian 13 in a second VM, accepting guided partitioning with LVM. Now compare the two first-boot systems on the three things the installers decided for you, by running the same commands on each VM:

# lsblk -f  # partition and LVM layout, and the filesystems
# systemctl is-active firewalld ufw  # is a host firewall running at all?
# getent group sudo wheel  # which group holds the admin user you created

The differences are the lesson. AlmaLinux comes up with firewalld active and your admin in the wheel group; Debian comes up with no firewall running and your admin in the sudo group; and the two partition layouts reflect each installer's defaults. Those exact divergences return as whole chapters later (Chapter 5 for the become-root group, Chapter 10 for the firewall gap that a fresh Debian ships with). Snapshot both clean installs now; every later lab starts from these.

Exercise

You need fifty identical AlmaLinux servers. Which artifact from a single interactive install lets you build the other forty-nine unattended, where does it live, and what is the one-sentence reason an enterprise distribution ships this by default while Arch does not?

Part II The Core System

The things you do in the first hour on any new host: install software, make accounts, lay out disks, and run services. This part teaches each across the families, leaning hardest on packaging, where the philosophies are loudest, and converging on systemd, where they finally agree.

Chapter 4Packages and Release Models

Package management is where a distribution's character is most exposed: what it will install, from where, how it vouches for it, and how often it changes.

Learn the model behind the commands and the commands stop needing memorization. This is the chapter that most rewards seeing the families side by side.

4.1 Two formats, four managers, three philosophies

Underneath, there are two dominant package formats and a rolling-source model. Debian and Ubuntu use .deb packages, manipulated at a low level by dpkg and at a usable level by apt, which resolves dependencies and talks to repositories. The Red Hat family uses .rpm packages under dnf (the successor to yum), with the same low-level/high-level split via the rpm command. Arch uses pacman against a rolling repository, plus the Arch User Repository (AUR), which ships build recipes rather than binaries. The table is the cheat sheet; the sections after it are the reasoning.

FamilyFormatLow levelHigh levelRelease modelInstall a package
Debian / Ubuntu.debdpkgaptfixed release; Debian slow, Ubuntu LTS every 2 yrapt install git
RHEL / AlmaLinux.rpmrpmdnffixed, long-lived enterprise releasednf install git
Fedora.rpmrpmdnffast, ~6-month cadence (the upstream)dnf install git
Archpkg.tar.zstpacmanpacman / AUR helperrolling; no versionspacman -S git

4.2 Debian and Ubuntu: apt, and the release model that defines them

On Debian and Ubuntu the daily commands are the same: apt update refreshes the package index, apt install adds software, apt upgrade applies updates, apt full-upgrade allows removals to satisfy bigger changes, which makes it the one verb here that can bite: it will uninstall packages to resolve a dependency, so on a system you care about you read the removal list it prints before confirming (or run apt -s full-upgrade to rehearse it first), and you snapshot or back up beforehand, the patching discipline of Section 4.5 and the backups of Section 17.1. What differs is the model behind the repository. Debian maintains three rolling streams (stable, testing, unstable) and promotes packages between them slowly; "stable" means old and trusted, on purpose. Ubuntu freezes Debian's testing into a release on a clockwork cadence and supports it for years.

Ubuntu then adds two things Debian does not ship by default, and both matter operationally. PPAs (Personal Package Archives) let anyone publish a repository you can add with one command; they are how you get newer software than Ubuntu ships, and also how you get software nobody vetted. Snap packages bundle an application with its dependencies and update themselves out of band from apt, which is convenient and occasionally surprising when a snap updates a service you thought was frozen.

Caution

A PPA is an arbitrary third party with root-level reach: installing from one means trusting its maintainer not to ship malicious or broken packages, and trusting them to keep doing so. Treat add-apt-repository ppa:... the way you would treat curl | sudo bash. For a server, prefer the distribution's own repositories; where a PPA is unavoidable, pin it to the single package you need and record why, so the next administrator (possibly you) knows what is trusted and what is not.

4.3 The Red Hat family: dnf, modules, and the Fedora pipeline

On RHEL, AlmaLinux, and Fedora the verbs rhyme: dnf install, dnf upgrade, dnf remove, with dnf check-update to look before you leap. The interesting structure is where the packages come from. Fedora is the proving ground: new toolchains, new defaults, new kernels land there first. Periodically Red Hat forks a moment of Fedora into a RHEL major version and supports it for a decade, changing very little after. AlmaLinux rebuilds that RHEL source so you can run the same system for free. Understanding this pipeline explains the family's whole personality: RHEL is conservative because being the stable end of a fast pipe is its entire job, and Fedora is willing to break things because being the unstable end is its job.

The pipeline also explains why AlmaLinux and Rocky exist at all, and why many shops prefer a rebuild to RHEL itself. They are binary-compatible reconstructions of RHEL: the same packages built from the same source, so software a vendor certified against RHEL runs on them unmodified and an administrator's RHEL knowledge transfers one to one. They filled a real gap when Red Hat redirected CentOS to a rolling "Stream" model in 2020 and the community wanted the old drop-in-for-RHEL guarantee back. The draw is concrete: RHEL's stability and ecosystem without the per-system subscription, which is exactly why a free rebuild, rather than Fedora, is this book's Red Hat lab bench.

Standard · CIS: verify package signatures

Every CIS Linux Benchmark requires that package-manager signature checking stay enabled, because a package manager that installs unsigned packages will happily install a tampered one. On the Red Hat family this is gpgcheck=1 in /etc/dnf/dnf.conf and in every repo file; on Debian and Ubuntu it is apt's signed-repository mechanism, which is on by default and which you defeat the moment you reach for --allow-unauthenticated. Do not disable it to make an install "just work"; an install that only works unsigned is telling you something.CIS Red Hat Enterprise Linux 10 Benchmark v1.0.1 and CIS Debian Linux 13 Benchmark v1.0.0, package-management integrity sections; mirrored in the Distribution-Independent Linux Benchmark v2.0.0. Verify the exact section numbers against the current benchmark, which renumbers between revisions.

4.4 Arch: pacman, the AUR, and its real limit

Arch installs official packages with pacman -S and updates the whole system with pacman -Syu, which you run often because there is no other kind of update; a rolling release is always either current or neglected. The official repositories are small, curated, and signed. The AUR is the opposite: a vast collection of user-submitted build recipes (PKGBUILD files) that an AUR helper downloads and builds locally.

Here is a place this book applies its own rule about absent authority. There is no security review, no signing guarantee, and no organizational vetting standing behind an AUR package; the Arch project is explicit that the AUR is used at your own risk. That is not a reason to avoid Arch, but it is a reason to be deliberate: read every PKGBUILD before you build it, prefer the official repositories when a package exists in both, and never run an AUR helper as root. The recommendation here is not "trust the AUR" or "shun the AUR"; it is "the AUR is unvetted by design, so supply the review yourself, because no one else will."

Where this leaves Arch in production

The same property that makes the AUR powerful (anyone can publish, instantly) makes a rolling, partly-unvetted system a poor fit where you must certify a fixed configuration against an external baseline; Chapter 13 returns to this when no STIG or CIS Benchmark exists for Arch at all. Arch's strength is the learning and the control; its limit is the compliance story, and pretending otherwise would not be doing you a favor.

4.5 Patching, the shared discipline

Whatever the family, the production question is the same: how do security updates reach this host without a human remembering? Debian and Ubuntu answer with unattended-upgrades, which can apply security updates automatically; the Red Hat family answers with dnf-automatic; Arch answers with "you, on a schedule," which is the unavoidable answer for a rolling release and a real operational cost. The mechanism differs; the principle does not, and it is one of the few places this book will simply tell you what to do.

Standard · Timely patching is a control, not just hygiene

Keeping a system current on security updates is a compliance requirement in its own right, not merely good practice. NIST SP 800-53 SI-2 (Flaw Remediation) requires known vulnerabilities to be fixed within defined timeframes, and both the CIS Benchmarks and the DISA STIGs carry controls requiring that security updates be installed and current, with CIS additionally recommending that automatic updates be configured. Automating patches with unattended-upgrades or dnf-automatic is therefore not only operationally sensible, it is how you reliably satisfy the control, because a host patched "when someone remembers" fails the audit the week someone does not.NIST SP 800-53 Rev 5, control SI-2; CIS Benchmark and DISA STIG patch-currency controls, plus the CIS automatic-update recommendation. Confirm the exact item and finding identifiers in the current benchmark, STIG, and SCAP profile (Chapter 13) rather than citing a number from memory.

Best practice

Turn on automatic security updates on every server from day one, and reboot on a schedule you choose rather than one an exploit chooses for you. Unattended security patching plus a planned weekly reboot window beats a hand-curated patch process that slips the moment you are busy, which is always. Reserve manual control for feature upgrades, never for security fixes.

Lab 3 · Install the Grimoire Box service two ways

Goal: install the same Git server package on Debian 13 and AlmaLinux 10, and watch the model, not just the command, differ.

# Debian/Ubuntu
# apt update && apt install -y git
# dpkg -l git  # confirm the installed version and that apt verified its signature

# RHEL/AlmaLinux  (git daemon is a separate subpackage here, unlike Debian)
# dnf install -y git git-daemon
# rpm -qi git  # note the .el10 release tag and the signing key

Compare the versions you got. The Debian package will often be a slightly older upstream release than the AlmaLinux one or vice versa, and both will be older than Fedora's; that is the release model showing through, not a mistake. One packaging difference bites the running example directly: the git daemon command this book serves on port 9418 ships in the main git package on Debian, but in a separate git-daemon subpackage on the Red Hat family, which is why the AlmaLinux line above names it explicitly. Omit it and the service in Chapter 7 starts and then immediately exits, because git daemon is not installed. Record both versions in your lab notes; Chapter 21 will have you do exactly this on a system you did not build.

Exercise

You need a newer version of a tool than Debian stable ships. List two ways to get it and one risk of each, and say which you would choose for a server that must stay supported for three years.

Chapter 5Users, Groups, PAM, and sudo

Every security property of a host rests on three questions: who exists, who may log in, and who may become root.

Linux answers them with a small set of text files, a pluggable authentication stack, and sudo, and the concepts are shared across families even where the file names and helper tools differ. Get this chapter right and most of the hardening later is just tightening what you set up here.

5.1 Users, groups, and the shadow suite

Accounts live in three files you can read right now: /etc/passwd (one line per user: name, UID, primary group, home, login shell), /etc/group (group memberships), and /etc/shadow (the hashed passwords and aging rules, readable only by root). Not every account is a person: low UIDs are system accounts that own services and cannot log in interactively (the Grimoire Box's git service account is one), while human users get UIDs from 1000 up. You manage them with useradd/usermod/userdel and groupadd, and the passwd and chage tools set and age passwords. This is identical across the families; the conventions (default UID ranges, whether a user gets a private group) vary slightly and are worth confirming with useradd -D on the box.

# useradd -r -s /usr/sbin/nologin -d /srv/git git  # a system account that cannot log in
# useradd -m -s /bin/bash alice  # a human admin, with a home and a shell
# passwd alice

5.2 PAM: the gate every login passes through

When something authenticates a user (login, SSH, sudo), it does not check the password itself; it asks PAM, the Pluggable Authentication Modules framework. PAM runs a stack of small modules for each of four phases: auth (prove identity), account (is the account allowed and unexpired), password (rules for changing it), and session (set up the session). The stacks live in /etc/pam.d/, and editing them is how you enforce password quality and account lockout. This is the same framework everywhere, but the family layout differs in a way you must know: Debian and Ubuntu factor shared rules into common-auth, common-password, and friends, while the Red Hat family uses system-auth and password-auth, which on RHEL 9 and 10 you do not hand-edit but generate with authselect.

Caution

PAM is the one place a careless edit locks everyone out, including you, because a broken auth stack can deny every login at once. Keep a second root session open while you change PAM, test in it before you close your working session, and on the Red Hat family prefer authselect to editing system-auth by hand, because a manual edit there is reverted (or fought) by the tool that owns the file.

5.3 sudo, and the group that grants it

Nobody should log in as root; you log in as yourself and escalate with sudo, which logs who did what. Its policy lives in /etc/sudoers and drop-in files under /etc/sudoers.d/, and you edit them only with visudo, which checks the syntax before saving. The families differ in which group confers sudo: on Debian and Ubuntu it is the sudo group, on the Red Hat family and Arch it is wheel. Adding an admin is therefore a one-line difference you should internalize:

# usermod -aG sudo alice  # Debian/Ubuntu
# usermod -aG wheel alice  # RHEL/AlmaLinux/Fedora, and Arch
Caution

Always edit sudo policy with visudo (or visudo -f /etc/sudoers.d/myfile), never with a plain editor. A syntax error saved directly into /etc/sudoers can break sudo entirely, and if you have already disabled the root password you have locked yourself out of privilege on the box. visudo refuses to save a file that would do this.

Using visudo without learning vi

Here is the part nobody mentions, which is exactly why newcomers quietly give up on visudo and edit /etc/sudoers in nano (losing the safety check): visudo opens vi by default. You do not have to learn vi. visudo respects your EDITOR, so EDITOR=nano visudo gives you nano with the syntax check still in place, which is the best of both. And if you are ever dropped into vi with no choice, the survival kit is four keystrokes: i to start typing, Escape to stop, then :wq and Enter to save and quit (or :q! to abandon the change). The goal is to keep the check visudo gives you, not to win an argument with an editor.

Best practice

Grant the narrowest sudo that does the job. Full alice ALL=(ALL) ALL is fine for a human administrator, but a deploy account that only needs to restart one service should get exactly that (deploy ALL=(root) /usr/bin/systemctl restart grimoire-git), not blanket root. Every unnecessary grant is a finding waiting to happen and a bigger blast radius if the account is compromised.

5.4 wheel versus sudo, and where this goes next

Why does the Red Hat family grant administration through a group called wheel while Debian uses one called sudo? History, not magic. wheel is the old Unix and BSD convention for "the users allowed to become the superuser" (from the slang "big wheel" for someone important), and the Red Hat family kept it; its sudoers ships a %wheel ALL=(ALL) ALL line. Debian chose to name a dedicated group after the tool itself, sudo, for plainness. Mechanically they are identical: both are ordinary groups that a line in /etc/sudoers happens to grant privilege to, and you could rename or swap them by editing that line. Knowing the names are a convention rather than something built in is what lets you read any system's sudoers and see who actually has root, instead of assuming the group name tells you.

This is discretionary control; mandatory control is the next layer

Everything in this chapter, ownership, groups, and sudo, is discretionary access control: the owner of a thing decides who may use it, and root may do anything. The layer above it is mandatory access control, SELinux on the Red Hat family and AppArmor on Debian, which confines even a privileged, root-running process to what a system-wide policy allows regardless of who owns what. This book introduces it in Chapter 15; both SELinux and AppArmor are deep enough to earn their own Grimoire volumes, and the users-and-sudo groundwork here is what makes that confinement make sense when you reach it.

The mechanisms this chapter introduced as raw parts, password quality and lockout (pam_pwquality and pam_faillock) and key-based SSH login, are hardened to a named standard in Chapter 14; SSH specifically, the door you will actually expose, is Chapter 9; and the standards that dictate exact values (a minimum password length, a lockout threshold) are gathered in Chapter 13, because they differ by family and by baseline.

Lab 4 · The Grimoire Box accounts on both families

Goal: create the service account and an administrator on Debian 13 and AlmaLinux 10, and feel the one real difference (the sudo group) against the many similarities.

On each VM: create the git system account and an alice admin as in 5.1, then grant alice sudo using the correct group for that family, and confirm:

$ sudo -l -U alice  # list what alice may run as root
# getent group sudo wheel  # see which group exists and who is in it on this family

Note that everything except the group name was identical. Record which group each family used; the firewall and SSH chapters assume alice can escalate.

Exercise

A teammate edits /etc/sudoers directly in nano, fat-fingers a line, saves, and now sudo reports a syntax error for everyone. What one command should they have used that would have caught the error before saving, and what is the recovery path if the root password is already disabled?

Chapter 6Storage: Partitions, LVM, Filesystems, and Mounts

Storage is where "it works" and "it works in two years when the disk fills" part ways.

This chapter goes from a raw disk to a mounted, resizable, safely-optioned data volume for the Grimoire Box, covers the filesystem each family reaches for and why, and sets up the partition and mount choices that the hardening chapters will later check against a benchmark.

6.1 Disks, partitions, and GPT

A disk shows up as a block device (/dev/sda, /dev/vda on a VM, /dev/nvme0n1 on NVMe); lsblk draws the tree of disks, partitions, and what is mounted where, and is the first command to run on any storage question. Modern systems partition with GPT rather than the legacy MBR scheme, which removes the old four-primary-partition limit and the 2 TB ceiling. You can carve partitions directly, but on a server you rarely should, because a fixed partition is a decision you cannot easily revise. That is what LVM is for.

6.2 LVM: volumes you can grow

The Logical Volume Manager inserts a layer of indirection between partitions and filesystems so that storage becomes flexible. You mark partitions as physical volumes (pvcreate), pool them into a volume group (vgcreate), and carve logical volumes out of the pool (lvcreate) that you format and mount. The payoff arrives the day a volume is nearly full: you extend it and grow its filesystem online, with the service running, instead of taking an outage to repartition.

# pvcreate /dev/vdb
# vgcreate vg_data /dev/vdb
# lvcreate -L 20G -n lv_git vg_data
# # later, when /srv/git is filling up:
# lvextend -r -L +20G /dev/vg_data/lv_git  # -r grows the filesystem too, online

The indirection buys more than growth. Because logical volumes sit on a pool rather than on raw partitions, a volume group can span several disks (so a volume can be larger than any single disk), you can migrate data off a dying disk while the system runs with pvmove, and you can take a near-instant snapshot of a volume to get a consistent copy for a backup or a pre-upgrade safety net (Chapter 17). Thin pools go further and let you over-commit, allocating volumes that together promise more space than physically exists, on the bet they will not all fill at once.

Caution

That flexibility has sharp edges worth respecting. An LVM snapshot is copy-on-write and fixed-size; if it fills because the origin changed more than you budgeted, it is dropped and the backup it was feeding fails, so snapshots must be sized and watched, not set and forgotten. A volume group spanning several disks fails entirely if any one of them dies unless you mirrored it, so spanning is convenience, not redundancy. An over-committed thin pool that runs out of real space takes every thin volume on it down at once. And shrinking is genuinely dangerous: you must shrink the filesystem before the volume and get the order and sizes exactly right, which is why this book provisions modestly and grows on demand rather than over-allocating and trimming back.

6.3 Filesystems, and the family defaults

On top of a logical volume goes a filesystem, and the default a family chooses tells you what it optimizes for. ext4 (the Debian and Ubuntu default) is the conservative pick: mature, universally understood, hard to surprise, and resizable in both directions with resize2fs (it grows online, on the mounted volume, and shrinks offline, with the volume unmounted), which makes it a safe choice if you might ever need to reduce a volume; of the three here, only XFS cannot shrink. XFS (the Red Hat family default) trades that for scale: it handles very large volumes and heavy parallel I/O better, the enterprise-workload bias showing again, but it can only grow (xfs_growfs), never shrink. Btrfs is the ambitious one, adding snapshots, checksumming, and subvolumes at the filesystem layer itself; it is the default on openSUSE and on Fedora Workstation (since Fedora 33), AlmaLinux 10 offers it at install, and RHEL pointedly does not ship it, one of the few places a rebuild diverges from upstream. Its power (cheap snapshots, self-healing checksums) comes with more moving parts and some long-standing caveats (its built-in RAID 5/6 is still considered unstable), which is why conservative server shops often stay on XFS or ext4 and reach for Btrfs only when they specifically want its snapshotting. For most server volumes any of the three is fine; pick by whether you value maturity and the simplest shrink (ext4), raw scale at the cost of never shrinking (XFS), or filesystem-level snapshots (Btrfs, which also resizes both ways).

Default filesystem by family

Debian and Ubuntu: ext4 (grow or shrink with resize2fs). RHEL and AlmaLinux: XFS (xfs_growfs to grow; no shrink). Fedora is split: Server uses XFS while Workstation has defaulted to Btrfs since Fedora 33, a reminder that "the Fedora default" depends on which edition you mean. AlmaLinux additionally offers Btrfs at install; RHEL does not ship it. The asymmetry that bites in practice: XFS grows but never shrinks, while ext4 and Btrfs both grow and shrink, so if you might ever need to reduce a volume, provision it ext4 (or Btrfs) rather than XFS. Confirm what a given box actually runs with findmnt or lsblk -f.

6.4 Mounting, fstab, and the options that are security controls

A filesystem is attached to the tree at a mount point, and persistent mounts are recorded in /etc/fstab (or as systemd .mount units), keyed by UUID so they survive device renaming. The mount options are not just tuning; several are security controls that the benchmarks in Chapter 13 require on specific partitions. nodev stops a filesystem from carrying device files, and noexec forbids executing binaries from it. nosuid is the one that is not self-explanatory, and it is the most important of the three. Normally a binary with its setuid bit set runs with the privileges of its owner rather than the user who launched it, which is the controlled mechanism that lets passwd and sudo perform a root action on an ordinary user's behalf. The danger is an uncontrolled one: if an attacker can place a setuid-root binary of their own onto a filesystem (a data volume, a USB stick, an upload directory), running it would hand them root. nosuid tells the kernel to ignore setuid bits on that filesystem entirely, so a planted setuid-root binary there is just an ordinary program with no special powers. That is why the benchmarks want it on every filesystem meant to hold only data. Applied to /tmp, /var, /var/log, /home, and /dev/shm, the three together shrink the places an attacker can stage and run code.

Standard · CIS: separate partitions with nodev, nosuid, noexec

The CIS Linux Benchmarks require that several directories be on their own partitions and mounted with restrictive options: /tmp, /var, /var/tmp, /var/log, /var/log/audit, and /home, with combinations of nodev, nosuid, and noexec as appropriate to each. The rationale is containment: code an attacker drops in world-writable /tmp cannot execute if /tmp is noexec, and a planted device node is inert under nodev. This is one reason LVM at install time pays off, because creating these as separate volumes after the fact is far more work.CIS Red Hat Enterprise Linux 10 Benchmark v1.0.1 and CIS Debian Linux 13 Benchmark v1.0.0, the filesystem and partition sections (Section 1.1). Exact item numbers differ between the benchmarks and renumber across revisions; read them from the current benchmark or the SCAP profile (Chapter 13) rather than from memory.

Caution

A wrong line in /etc/fstab has two failure modes, and the quiet one is the more damaging. The loud one is obvious: a missing device or a typo drops the system into emergency mode at boot, before SSH is up, and you notice at once. The quiet one is worse. If a non-root filesystem fails to mount but the boot continues anyway (because you used nofail, or because the mount is not required for early boot), the system comes up looking healthy while a mount point sits empty, and every service then writes to the bare directory on the root filesystem underneath it. Your Git data lands in /srv/git on the root volume instead of on the data volume, the root filesystem quietly fills, and you discover the data volume never mounted only when something breaks or the data turns up in the wrong place. Always test a new fstab with mount -a before rebooting, use nofail deliberately rather than as a habit, and for a volume a service depends on, wire that dependency explicitly (a systemd mount ordering, or x-systemd.requires=) so the service refuses to start without its storage rather than writing into the void.

6.5 The Grimoire Box data volume

Putting it together for the running example: the Git repositories belong on their own LVM volume, separate from the root filesystem, so they can grow independently and be backed up and mounted with their own options. That separation is also what makes the backup chapter (Chapter 17) clean, because the data to protect is one well-defined volume rather than scattered across the root.

Lab 5 · A hardened data volume on both families

Goal: add a disk, make it an LVM volume, format it with the family's default filesystem, and mount it at /srv/git with security options, on Debian 13 and AlmaLinux 10.

# pvcreate /dev/vdb && vgcreate vg_data /dev/vdb
# lvcreate -L 10G -n lv_git vg_data
# mkfs.ext4 /dev/vg_data/lv_git  # Debian/Ubuntu default; use mkfs.xfs on AlmaLinux
# mkdir -p /srv/git
# # add to /etc/fstab (by UUID), with hardened options:
# # UUID=...  /srv/git  ext4  defaults,nodev,nosuid  0 2
# mount -a && findmnt /srv/git  # confirm it mounted with the options you set

Use nodev,nosuid here (a Git data volume has no reason to carry device nodes or setuid binaries); leave noexec off only if the service needs to run hooks from the volume. Note the single command that changed between families (mkfs.ext4 versus mkfs.xfs) against everything that did not.

Exercise

You provisioned /srv/git as a fixed 10 GB partition and it is now full. On an LVM-backed volume you would fix this in one online command; name it. Then say which default filesystem (ext4 or XFS) would let you later shrink a volume you over-allocated, and which would not.

Chapter 7Services and the System Manager: systemd in Depth

systemd is the layer where the families finally stop arguing.

The unit files, the management commands, the journal, and the sandboxing directives in this chapter are, with vanishingly few exceptions, identical on Debian, Ubuntu, AlmaLinux, Fedora, and Arch. That is precisely why it is the highest-leverage chapter in the book: learn systemd once and you can start, inspect, schedule, and confine services on any system you will ever meet. We use it to turn the Grimoire Box's Git daemon from a process that merely runs into a service that is supervised, logged, and confined. This chapter is the operating depth every administrator needs; systemd is vast enough that full mastery is its own Grimoire volume, which this one points to rather than reproduces.

7.1 The unit: systemd's one idea

Everything systemd manages is a unit: a small declarative file that describes a thing and how it relates to other things. The types you will meet are .service (a process to supervise), .socket (a listening socket), .target (a named synchronization point that groups other units, the modern replacement for runlevels), .timer (a scheduled trigger), .mount (a filesystem), and .slice (a cgroup for resource control). Ninety percent of the time you are writing a .service. Here is a minimal one for the Grimoire Box:

# /etc/systemd/system/grimoire-git.service
[Unit]
Description=Grimoire Box Git daemon
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/bin/git daemon --reuseaddr --base-path=/srv/git --export-all /srv/git
User=git
Group=git
Restart=on-failure

[Install]
WantedBy=multi-user.target

The three sections do three jobs. [Unit] carries the description and the relationships (After, Wants); [Service] says how to run the process and, later, how to confine it; [Install] is read only by systemctl enable and tells systemd where to hook the unit into the boot. One flag on the ExecStart line is load-bearing and easy to miss: git daemon refuses to serve any repository unless that repository contains a git-daemon-export-ok file, or the daemon is started with --export-all; without one of the two it binds the port and then answers every clone with "repository not exported." This book opts the whole --base-path in with --export-all, which is the right choice for a host that serves only its own repositories; the per-repository git-daemon-export-ok marker is the finer-grained alternative when you want to publish some repositories under a path but not others.

Where units live, and which one wins

Three directories hold units, in increasing precedence: /usr/lib/systemd/system (shipped by packages), /run/systemd/system (runtime), and /etc/systemd/system (yours). A unit in /etc overrides the vendor copy of the same name. To change just one directive without copying the whole file, drop a fragment in /etc/systemd/system/<unit>.d/*.conf; systemd merges it over the vendor unit. This layout is identical on every family in this book. These are the system instance's directories; each user's instance has its own parallel set, with the same precedence, covered in Section 7.6.

Caution

Never edit a vendor unit in /usr/lib/systemd/system directly: the next package update silently reverts your change, and the regression can take hours to find. The right way to override one is systemctl edit <unit>, which opens an editor, writes your changes to a drop-in at /etc/systemd/system/<unit>.d/override.conf, and runs daemon-reload for you (use systemctl edit --full <unit> to replace the whole unit instead). If you do edit a unit file by hand, you must run systemctl daemon-reload yourself afterward, or systemd keeps acting on the definition it loaded at boot and your change appears to do nothing.

7.2 Managing services with systemctl

One command drives all of it. The verbs that matter on day one:

# systemctl start grimoire-git  # run it now
# systemctl enable grimoire-git  # start it at every boot
# systemctl enable --now grimoire-git # both at once (the usual move)
# systemctl status grimoire-git  # state, recent log lines, the cgroup
# systemctl restart grimoire-git
# systemctl reload grimoire-git  # re-read config without a full restart, if supported
# systemctl disable --now grimoire-git
# systemctl mask grimoire-git  # stronger than disable: cannot start at all

The distinction beginners trip on is that start and enable are independent: start affects the running system now, enable affects every subsequent boot, and neither implies the other. mask is the heavy hammer: it points the unit at /dev/null so it cannot be started even as another unit's dependency, which is occasionally exactly what you want for a service a benchmark says must not run.

Best practice

Reach for enable --now by default so the running state and the boot state never silently disagree, which is a classic source of "it works until it reboots" incidents. Reserve mask for services you want to guarantee stay down; use plain disable when you might re-enable later.

7.3 Targets, dependencies, and the boot you already met

Targets group units and mark the milestones of the boot you followed in Chapter 1. On a server the default target is normally multi-user.target (a desktop adds graphical.target on top). Units declare relationships along two independent axes that are easy to confuse: Wants and Requires say whether one unit pulls in another (soft and hard respectively), while After and Before say in what order they start. They are orthogonal, and forgetting that is a real bug.

Requiring is not ordering

A unit that Requires another but does not also order itself After it will happily start before its dependency is ready, then fail intermittently in a way that looks like a race because it is one. If your service needs the network up, it needs both Wants=network-online.target and After=network-online.target, which is why the example in 7.1 carries both.

7.4 The journal

systemd captures each service's standard output and error, plus structured metadata, into the journal, which you read with journalctl. The flags you will use constantly:

# journalctl -u grimoire-git  # just this unit
# journalctl -u grimoire-git -f  # follow, like tail -f
# journalctl -u grimoire-git -r  # reverse: newest entries first
# journalctl -b  # this boot only
# journalctl -b -1  # the PREVIOUS boot: why did it go down?
# journalctl --list-boots  # every boot the journal still remembers
# journalctl -p err --since "1 hour ago"

Two of those earn their keep during an incident. -b scopes to the current boot, and -b -1 reads the boot before this one, which is how you learn why a machine that just rebooted went down (assuming a persistent journal, see below); --list-boots shows what is available to look back at. And -r simply reverses the order to newest-first, which is what you want when you only care about what just happened.

One default surprises nearly everyone on the systems this book runs on, so learn it before it bites. On Debian 13 and AlmaLinux 10, which both ship systemd 257, the compiled-in default is Storage=auto, which means "persist to /var/log/journal if that directory exists, otherwise keep the log in memory under /run and lose it on reboot." The two lab platforms then diverge on whether they create that directory, so they behave differently out of the box. AlmaLinux 10 is volatile by default: it does not create /var/log/journal, so on a fresh install journalctl shows you the current boot and last week is simply gone; you opt in by creating the directory or setting Storage=persistent and restarting systemd-journald. Debian 13 is persistent by default: it ships /var/log/journal (as Fedora does), so the journal survives a reboot with no action from you. The direction of travel is toward persistence everywhere: systemd v259 changed the upstream compiled-in default to Storage=persistent, so on a newer or differently-built system the journal may already survive a reboot regardless of the directory. Do not assume either way; check the box in front of you with journalctl --header or test -d /var/log/journal.

The families also differ in whether a plain-text syslog daemon runs alongside the journal at all. The Red Hat family ships rsyslog enabled, writing /var/log/messages. Debian 13 no longer installs rsyslog by default: a stock trixie box is journald-only, with no /var/log/syslog unless you add the package (Ubuntu still ships it, writing /var/log/syslog). Confirm both the journal default and whether a text-log daemon is even present on your own VM, since these drift between releases. Using the journal to actually troubleshoot a sick host is Chapter 18.

7.5 From running to confined: service sandboxing

Here is the payoff, and the reason this chapter sits before the security part. A modern systemd service can be heavily confined with declarative directives the kernel enforces, without writing a line of policy. You tell systemd what the service is allowed to touch, and it builds the sandbox. The high-value directives, added as a drop-in to the Grimoire Box's Git service:

# /etc/systemd/system/grimoire-git.service.d/hardening.conf
[Service]
NoNewPrivileges=true
ProtectSystem=strict  # /usr, /boot, /etc read-only
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/srv/git  # the only place it may write
CapabilityBoundingSet=  # drop every capability
SystemCallFilter=@system-service
RestrictAddressFamilies=AF_INET AF_INET6
MemoryDenyWriteExecute=true

Each line removes a class of things a compromised service could do: escalate privilege, write to system directories, see other users' home directories, share a /tmp with another service, wield Linux capabilities, make exotic syscalls, open non-IP sockets, or map memory that is writable and executable at once. systemd ships a tool that scores how exposed a unit is and tells you which directives would help:

# systemctl daemon-reload
# systemctl restart grimoire-git
# systemd-analyze security grimoire-git
  -> Overall exposure level for grimoire-git.service: ~4.0 OK
     (the same unit scored ~9.5 UNSAFE before the drop-in)
Standard · systemd.exec(5), and where the baselines are quiet

The authority for these directives is the systemd documentation, principally systemd.exec(5) and systemd.service(5), which define each option and its security effect; systemd-analyze security is the practical measure. It is worth saying plainly that this is a place the compliance baselines say very little: the CIS Benchmarks and DISA STIGs mandate system-wide settings (mount options, SSH, auditing) far more than they mandate per-service sandboxing, so there is usually no numbered control to cite for "confine this daemon." The recommendation here rests on the least-privilege principle and the systemd manual rather than a STIG finding. Apply it anyway; a confined service is the difference between a compromised process and a compromised host.systemd.exec(5) and systemd.service(5), freedesktop.org systemd manual (current series v260); systemd-analyze security for scoring. Start each directive permissive and tighten while watching the journal, because over-confining a service produces failures that look like bugs in the service. The absolute exposure number drifts upward as newer systemd adds checks, so compare your own before and after on one box rather than matching a printed figure.

Two more unit types round out the picture but are covered where they are used rather than here: .timer units schedule work and are the modern replacement for cron, and .slice units group services into cgroups so you can cap what they consume. Both belong to Chapter 11, scheduling and resource control.

7.6 User services: systemd in the user's dotfiles

Every unit so far has been a system unit, owned by root and managed by the system instance of systemd that is PID 1. There is a second systemd for every user. When you log in, the system starts a per-user instance, systemd --user, that supervises units out of your own home directory with no root involved at all. The unit syntax is identical to everything above; only the scope and the commands change. User units live in ~/.config/systemd/user/ (the dotfiles of the heading), with /etc/systemd/user/ and /usr/lib/systemd/user/ for admin- and vendor-supplied ones, and you drive them as an unprivileged user:

$ systemctl --user enable --now grimoire-sync.service
$ systemctl --user status grimoire-sync.service
$ journalctl --user -u grimoire-sync.service

The mechanism is not new; per-user systemd instances have existed for years. What is recent is the reason it suddenly matters on servers: rootless containers. A container run as an ordinary user with Podman becomes a user service, supervised by that user's systemd instance, so a break-out from the container lands in one unprivileged account rather than at root. That is a genuine defense-in-depth gain, and it is why a feature that used to be a desktop-session detail (it manages your audio and your session bus) has become a production technique in the last few years.

Caution

By default a user's systemd instance starts at login and stops shortly after that user's last logout, taking every user service down with it. A rootless container you start over SSH dies the moment you disconnect, which surprises everyone exactly once. The fix is to enable lingering for the account, which starts its user manager at boot and keeps it running with no active session:

# loginctl enable-linger alice  # alice's user services now start at boot and survive logout

Enable lingering for any user meant to run a long-lived service, and make a missing enable-linger the first thing you check when a user service "will not stay up."

For containers you rarely hand-write these units now. Podman's Quadlet (merged into Podman 4.4) lets you drop a declarative .container file in ~/.config/containers/systemd/ and have systemd generate the user service for you; the older podman generate systemd is deprecated in its favor. The rootless model, Quadlet, and running containers as managed services in depth are Chapter 19; this section is the systemd half of that story, so the two meet from both sides. Podman and the broader container story are likely to become their own Grimoire volume, so Chapter 19 covers what a Linux administrator needs and points there for container depth.

A user instance is not a smaller root

The per-user systemd cannot do everything the system instance can: it has no privileged system-wide reach, it binds low-numbered ports only with extra configuration, and it runs under the user's own XDG_RUNTIME_DIR and session bus. Use a user service for things that belong to a person or to a rootless workload, and a system unit for things that belong to the machine. The sandboxing directives from Section 7.5 work in both.

Lab 6 · Confine the Grimoire Box service on both families

Goal: harden the Git service with the drop-in above on Debian 13 and AlmaLinux 10, and confirm the work is identical on both, the convergence this chapter claims.

On each VM: create the service from 7.1, add the hardening drop-in from 7.5, then:

# systemctl daemon-reload
# systemd-analyze security grimoire-git  # note the score
# systemctl restart grimoire-git
# systemctl status grimoire-git  # confirm it still runs
# git init --bare /srv/git/test.git  # a repo to serve (exported by --export-all in 7.1)
# git ls-remote git://localhost/test.git  # POSITIVE leg: refs/exit 0, not "repository not exported"
# journalctl -u grimoire-git -b  # clean-security leg: no sandbox/AVC denials

Assert both legs, because a service that is "active" is not necessarily serving: the git ls-remote must succeed (a daemon missing --export-all, or a repo with no git-daemon-export-ok, listens on 9418 but refuses every clone), and the journal must show no sandbox denial. If the service fails after hardening, relax one directive at a time (a too-tight SystemCallFilter or a missing ReadWritePaths entry is the usual culprit) until it runs, then stop. The commands, the file paths, and the output are the same on both systems; that sameness is the point of learning this layer once.

Exercise

You add ProtectSystem=strict to a service that needs to write a cache under /var/cache/app, and it starts failing. Without removing ProtectSystem, what one directive fixes it, and why is that better than loosening ProtectSystem back to false?

Part III Networking and Access

A server exists to be reached, and a server's worst day starts with being reached by the wrong party. This part covers getting on the network, getting in safely over SSH, controlling what the host will answer, and keeping a service from eating the machine.

Chapter 8Interfaces, DNS, and Routing

A server exists to be reached, so this is non-negotiable ground, and it is where the families look most different while doing the most identical thing.

The kernel's networking is the same on all of them, and the tools to inspect it are the same; what differs is the configuration front end each bolts on top. Learn the kernel-level view first and the front ends become interchangeable rather than intimidating.

8.1 The view that is the same everywhere

Whatever configures it, you inspect the network with one modern toolkit, iproute2, which long ago replaced ifconfig and netstat (both deprecated, sometimes absent). Three commands answer most questions, identically on every family:

$ ip -br addr  # interfaces and their addresses, one line each
$ ip route  # the routing table: where traffic goes
$ ss -tlnp  # listening TCP sockets and the processes behind them

Learn these first, because they are the ground truth: no matter which front end claims to have configured an address, ip addr tells you what the kernel actually has.

8.2 The front ends, where the families diverge

Above the kernel, each family chooses a different manager, and this is the real content of the chapter. The Red Hat family uses NetworkManager, driven by nmcli, storing connections as keyfiles (the older ifcfg network-scripts are deprecated). Debian still defaults to classic ifupdown with /etc/network/interfaces. Ubuntu uses Netplan, a YAML description in /etc/netplan that renders down to systemd-networkd on servers. And systemd-networkd is the systemd-native option that minimal systems and containers often pick directly. Arch, characteristically, ships none active and has you choose.

Caution

One interface, one manager. The most common self-inflicted network outage is two managers fighting over the same NIC: NetworkManager and systemd-networkd both trying to own eth0, or a hand-edited ifupdown stanza for an interface NetworkManager also controls. Decide which manager owns an interface and make sure the others leave it alone, or the address will flap depending on who configured it last.

8.3 Names, and the resolver bugs that waste afternoons

Turning a name into an address is a separate subsystem, and it is where a large share of "the network is broken" tickets actually live, because the symptom (a name does not resolve) is one step removed from the cause. /etc/nsswitch.conf sets the lookup order (files, then DNS); /etc/hosts is the local override; and the DNS servers are listed in /etc/resolv.conf, which on modern systems is often a symlink managed by systemd-resolved (a stub resolver listening on 127.0.0.53), by NetworkManager, or by Netplan. The classic failure is a host that reaches everything by IP but nothing by name: the cause is almost always a stale or empty resolv.conf, a stopped resolved, or a resolver pointing at a server it can no longer reach.

Find out who owns resolv.conf before you edit it

Editing /etc/resolv.conf by hand on a system where systemd-resolved or NetworkManager manages it is futile: your change is overwritten on the next event. Run ls -l /etc/resolv.conf first; if it is a symlink into /run/systemd/resolve/, the resolver is managed and you configure DNS through that manager, not the file. This one check prevents a frustrating loop.

8.4 Servers want a stable address

A server should not depend on a floating DHCP lease that can change at the worst moment. Give it a static address, or a DHCP reservation pinned to its MAC, so that the host the firewall rules and the SSH config name is the host that is actually there tomorrow. The mechanism differs by front end; the principle does not.

Lab 7 · A static address, two front ends

Goal: set a static IPv4 address on AlmaLinux 10 with NetworkManager and on Debian 13 with its native tooling, then prove with the kernel-level tools that both worked.

# AlmaLinux 10 (NetworkManager)
# nmcli con mod "System eth0" ipv4.addresses 192.0.2.20/24 ipv4.gateway 192.0.2.1 \
    ipv4.dns 192.0.2.1 ipv4.method manual
# nmcli con up "System eth0"

# confirm on either family, the same way:
$ ip -br addr show eth0
$ getent hosts deb.debian.org  # proves DNS resolution works

On Debian, make the equivalent change in /etc/network/interfaces (or /etc/netplan on Ubuntu) and bring the interface back up. Note that the verification step, ip addr and a name lookup, was identical regardless of how you got there.

Exercise

A host pings 8.8.8.8 fine but cannot resolve any hostname. List the three files or services you would check, in order, and say which single command tells you whether /etc/resolv.conf is hand-managed or owned by a resolver.

Chapter 9SSH as the Control Plane, Done Safely

SSH is the door you almost always leave open, which makes it the single most important thing to get right, and the good news is that it is the same OpenSSH on every family, so this chapter is portable end to end.

We move the Grimoire Box from password logins to keys, turn off the things that get hosts compromised, and learn to verify the running configuration instead of trusting the file.

9.1 OpenSSH, and reading the effective config

The server is sshd, configured by /etc/ssh/sshd_config and increasingly by drop-in files under /etc/ssh/sshd_config.d/. The single most useful habit is to stop guessing what a setting is and ask the daemon: sshd -T prints the effective configuration after all files and defaults are merged, which is the only authority that matters during an audit or an incident.

# sshd -T | grep -Ei 'permitrootlogin|passwordauth|ciphers'  # what is actually in effect
# sshd -t  # validate config before reloading

9.2 Keys, and turning off passwords

Password authentication is brute-forceable and should be replaced by keys. Generate a modern key (ssh-keygen -t ed25519), install the public half in the server account's ~/.ssh/authorized_keys (ssh-copy-id does this), confirm you can log in with the key, and only then disable passwords. The order matters: prove the key works before you remove the fallback, or you lock yourself out.

9.3 The settings that matter, and where the family helps

A short list of sshd_config changes removes most SSH risk: PermitRootLogin no (log in as a user, escalate with sudo), PasswordAuthentication no and KbdInteractiveAuthentication no (keys only), AllowGroups to whitelist who may connect, and an idle timeout via ClientAliveInterval. Put these in a drop-in under sshd_config.d/ so a package update does not fight your edit. One genuine family difference is worth knowing: on the Red Hat family the approved ciphers, MACs, and key-exchange algorithms are set centrally by system-wide crypto policies (update-crypto-policies --set DEFAULT|FUTURE|FIPS), so you change SSH's cryptography for the whole system at once, whereas on Debian you set Ciphers, MACs, and KexAlgorithms per service in sshd_config.

Standard · DISA STIG and CIS: the SSH baseline

Both the DISA STIG and the CIS Benchmarks devote a substantial section to sshd: disabling root login, forbidding empty passwords, setting a login banner, capping MaxAuthTries, enforcing idle-session timeouts via ClientAliveInterval and ClientAliveCountMax, and restricting ciphers/MACs/KEX to an approved set. These are among the most-checked findings in any Linux audit. The exact values are version-specific and differ slightly between the STIG and CIS, and between families; pull them from the SCAP profile (Chapter 13) rather than hardcoding them here.DISA RHEL 9 STIG (current v2r8) and Canonical Ubuntu 24.04 STIG (v1r5), SSH server findings; CIS Benchmarks, the SSH section (commonly Section 5). On the Red Hat family, confirm the effective algorithms with update-crypto-policies --show and sshd -T, because the crypto policy can override what sshd_config appears to say.

Caution

Never harden SSH down a connection you cannot afford to lose without a safety net. Keep your current session open, validate the new config with sshd -t, reload in a way you can reverse, and open a second connection to confirm you can still get in before you close the first. A wrong AllowGroups or a disabled password with no working key has locked out more administrators than any attacker.

9.4 Reaching past the bastion

In a real network the Grimoire Box may not be directly reachable; you reach it through a jump host. OpenSSH does this natively with ProxyJump (ssh -J bastion grimoire-box), so you do not have to weaken the internal host's exposure to administer it. Bastion patterns and certificate-based SSH are a deeper topic; the principle for now is that the internal service host should be reachable only through a controlled path, which the firewall in Chapter 10 enforces.

Lab 8 · Keys-only SSH on both families

Goal: convert Debian 13 and AlmaLinux 10 to key-only SSH for the alice account from Chapter 5, and verify with sshd -T rather than by trusting the file.

$ ssh-keygen -t ed25519 -C "alice@workstation"
$ ssh-copy-id alice@grimoire-box
$ ssh alice@grimoire-box  # confirm the key works BEFORE the next step
# /etc/ssh/sshd_config.d/10-hardening.conf
#   PermitRootLogin no
#   PasswordAuthentication no
# sshd -t && systemctl reload ssh  # 'sshd' on the Red Hat family; 'ssh' on Debian/Ubuntu
# sshd -T | grep -i passwordauthentication  # expect: no

Note the one packaging difference you will hit: the service unit is named sshd on the Red Hat family and ssh on Debian and Ubuntu. Everything else, including the config and the verification, was identical.

Exercise

You set Ciphers in sshd_config on an AlmaLinux host, reload, and sshd -T still shows a different set. What system-wide mechanism is overriding you, and what one command shows you the policy currently in force?

Chapter 10The Host Firewall: nftables, firewalld, and ufw

A host firewall decides what the machine will even answer, and like networking it is one kernel engine wearing different faces per family.

Underneath is nftables; on top sits firewalld on the Red Hat family and ufw on Debian and Ubuntu. Learn the model (default-deny, then allow what you mean to expose) and the front end is just syntax. There is also one default you must not assume, covered below, because it differs and it is a security gap.

10.1 One engine, several faces

The kernel firewall is nftables, which replaced the older iptables. You rarely write raw nftables rules day to day, because each family ships a friendlier front end that generates them: firewall-cmd driving firewalld on the Red Hat family, and ufw on Debian and Ubuntu. When a front end cannot express what you need, you can drop to nft directly, but for a single service host the front end is enough.

Caution: the default firewall state is not the same

This is the divergence that catches people. A freshly installed Red Hat family system runs firewalld active by default, so it starts mostly closed. A fresh Debian has no active firewall at all, and Ubuntu ships ufw installed but inactive. So a new Debian or Ubuntu host is wide open at the host layer until you do something about it, while an AlmaLinux host is not. Never assume a Debian-family box is protected because an AlmaLinux box would have been; verify with nft list ruleset on any new system and treat an empty ruleset as the gap it is.

10.2 firewalld and zones (Red Hat family)

firewalld organizes rules into zones, each a named trust level with its own allowed services; an interface is assigned to a zone, and the default zone is public. You allow a service by name or port, make it permanent, and reload:

# firewall-cmd --add-service=ssh --permanent
# firewall-cmd --add-port=9418/tcp --permanent  # git daemon
# firewall-cmd --reload
# firewall-cmd --list-all  # what the active zone allows

10.3 ufw (Debian and Ubuntu)

ufw ("uncomplicated firewall") lives up to the name: you allow ports or services and enable it. The catch from 10.1 is that you must enable it at all, and you must allow SSH before you do, or you cut your own remote session:

# ufw allow OpenSSH  # allow SSH FIRST
# ufw allow 9418/tcp  # git daemon
# ufw enable  # turns on default-deny inbound
# ufw status verbose

10.4 The posture: default-deny, then allow on purpose

Whatever the front end, the Grimoire Box ships the same posture: deny inbound by default, allow exactly SSH and the service port, and nothing else. That is the entire model, and it is what the benchmarks check.

Standard · CIS and DISA STIG: a configured, default-deny host firewall

The CIS Benchmarks and the DISA STIGs require a host firewall to be installed, enabled, and configured to deny traffic by default, allowing only explicitly permitted services. The control exists precisely because of the default-state gap in 10.1: a host with no firewall, or a firewall left disabled, is a finding regardless of what an upstream network firewall does, because defense in depth assumes the host can be reached directly. CIS and the STIG name the specific tool per family (firewalld or nftables on the Red Hat family, ufw or nftables on Ubuntu).CIS Red Hat Enterprise Linux 10 Benchmark v1.0.1 and CIS Debian Linux 13 Benchmark v1.0.0, host-based firewall sections; DISA RHEL 9 STIG firewall findings. Confirm the required tool and default-deny wording in the current benchmark; the SCAP profile in Chapter 13 checks it directly.

Lab 9 · Default-deny on both families

Goal: bring the Grimoire Box to a default-deny posture allowing only SSH and the git port, using firewalld on AlmaLinux 10 and ufw on Debian 13, and confirm both reduced to the same kernel ruleset.

Apply the firewalld commands from 10.2 on AlmaLinux and the ufw commands from 10.3 on Debian, then compare the result the same way on both:

# nft list ruleset | less  # the actual kernel rules both front ends generated
# ss -tlnp  # cross-check what is still listening

On the Debian box, confirm first that the pre-firewall ruleset was empty (the 10.1 gap), so you can see the firewall actually changed the posture rather than decorating one that already existed.

Exercise

You hand a teammate a fresh Debian server and a fresh AlmaLinux server and say "both are firewalled by default." For which one is that false, what single command proves it, and which mistake during ufw enable over SSH would lock you out?

Chapter 11Time, Scheduled Work, and Resource Control

Three smaller subsystems that share a chapter because they share a theme: keeping the machine honest with itself.

A correct clock, work that runs on schedule, and limits that stop one service from starving the rest. Each is mostly convergent across families, with one or two differences worth naming.

11.1 Time, and why a wrong clock breaks everything

A clock that drifts is not a cosmetic problem: TLS certificate validation fails when the clock is wrong, log timelines from different hosts stop lining up, and authentication systems like Kerberos refuse to work outside a tight time window. So every server must synchronize its clock. The mechanism has a small family split: Debian and Ubuntu enable systemd-timesyncd by default, a lightweight SNTP client that is fine for keeping a single host roughly correct, while the Red Hat family uses chrony, a full NTP implementation that is also the right choice on any server that needs accurate, disciplined time. Check it with chronyc tracking (chrony) or timedatectl (either).

timesyncd is not chrony

systemd-timesyncd is a client only: it sets the clock from a server but cannot serve time or discipline it as precisely. For a server that other machines trust for time, or that has strict accuracy needs, install and enable chrony even on Debian and Ubuntu. For a lone host that just needs to not drift, the default timesyncd is enough. Confirm which is running with timedatectl show and do not run both.

11.2 Scheduled work: cron and systemd timers

Two systems run work on a schedule. The classic is cron (crontab -e for a user, /etc/crontab and /etc/cron.d/ for the system), simple and universal. The modern alternative is the systemd timer, a .timer unit that triggers a .service, which costs a little more to write but buys real advantages: its output lands in the journal, it can depend on other units, and a Persistent=true timer catches up a run it missed while the machine was off, which a plain cron job does not.

# /etc/systemd/system/grimoire-backup.timer
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
Best practice

For new scheduled work on a systemd system, prefer a timer over a cron job. When a backup silently stops running, the timer's journal entry and explicit last-run state make the failure visible, whereas a broken cron job fails into an email nobody reads or into silence. Keep cron for quick, personal, or legacy tasks; reach for timers for anything whose failure you would want to notice.

11.3 Resource control: cgroups v2 and systemd limits

The kernel mechanism that stops one service from consuming the whole machine is control groups, and every current family now uses the unified cgroups v2 hierarchy by default. You do not have to touch it directly, because systemd exposes it through unit directives: add CPUQuota, MemoryMax, MemoryHigh, and TasksMax to a service and the kernel enforces them. Capping the Grimoire Box's Git service means a runaway clone or a fork bomb in one repository cannot take down SSH and everything else on the box.

# /etc/systemd/system/grimoire-git.service.d/limits.conf
[Service]
CPUQuota=50%
MemoryMax=512M
TasksMax=256
# systemctl daemon-reload && systemctl restart grimoire-git
# systemd-cgtop  # live per-service CPU and memory, top-style

These directives are part of the same systemd you learned in Chapter 7, and they work identically on every family, because cgroups v2 is now universal rather than a per-distro variable.

Lab 10 · Cap the service and schedule a job

Goal: put CPU and memory limits on the git service and confirm the kernel enforces them, then schedule a daily task as a systemd timer, on both families identically.

# # add the limits drop-in above, reload, restart, then watch:
# systemd-cgtop
# systemctl show grimoire-git -p MemoryMax -p CPUQuotaPerSecUSec  # confirm they took

Then create the grimoire-backup.timer from 11.2 with a matching one-line .service, enable it with systemctl enable --now grimoire-backup.timer, and confirm it is scheduled with systemctl list-timers. Everything in this lab is byte-for-byte identical on Debian and AlmaLinux.

Exercise

A nightly job must run even if the server was powered off at its scheduled time and is booted later. Which systemd timer directive makes it catch up, and name one other advantage a timer has over the equivalent cron job for a job whose silent failure you need to detect.

Part IV Security, Hardening, and Standards

Now make it defensible, and prove it. This part builds the threat model, applies a named baseline with real tooling, hardens the pieces a baseline cannot fully express, and ends with the cross-family crosswalk that lets one configuration answer to several authorities at once. It is also where the difference between the families stops being a matter of taste and becomes a matter of what you are even allowed to run.

Chapter 12The Threat Model for a Linux Host

Before applying a single hardening setting, it is worth knowing what you are defending against, because a control you cannot explain is a control you will disable the first time it is inconvenient.

This short chapter frames the threats a Linux host actually faces and maps them to the rest of the book, so the baseline in the next chapters reads as reasoning rather than ritual.

12.1 What you are defending, and from whom

A production host faces a small number of realistic threats, and naming them organizes everything that follows. There is the remote attacker probing the services you expose (answered by the firewall in Chapter 10 and the SSH hardening in Chapter 9). There is privilege escalation, the attacker or buggy process that gets a foothold as an unprivileged user and tries to become root (answered by least-privilege accounts and sudo in Chapter 5, service sandboxing in Chapter 7, and mandatory access control in Chapter 15). There is the supply chain, the tampered or outdated package (answered by signed repositories and patching in Chapter 4). And there is inherited misconfiguration, the host that was wrong before you ever touched it (answered by the assessment and recovery in Chapter 21).

12.2 Two layers: the service, and the system under it

There are two distinct things to harden and it is worth keeping them separate. One is the application: the web app's input validation, its authentication, its dependencies. The other is the system the application runs on: the accounts, the kernel settings, the firewall, the service confinement. This book hardens the system layer, the part every host needs regardless of what it runs; the application layer is its own subject (the PHP volume is one example of it). Knowing which layer a given control belongs to keeps you from expecting a firewall to fix an application bug, or a code review to fix an open SSH password login. The standard reference for the system layer on a general-purpose server is NIST SP 800-123 (Guide to General Server Security), which draws exactly this line and catalogs the host controls that follow from it; Part IV of this book is, in effect, SP 800-123 applied across the Linux families.

12.3 Why a baseline is a threat model in disguise

The reason this book applies a named baseline rather than a personal checklist is that a STIG or CIS Benchmark is a threat model that a large community has already argued over. Each rule exists because someone traced a real attack to a real setting: "disable root SSH login" answers credential-stuffing the most powerful account; "noexec on /tmp" answers code dropped in world-writable space; "SELinux enforcing" answers a compromised service reaching beyond its job. Read a baseline this way, as a catalog of threats with their countermeasures attached, and applying it in Chapter 13 stops being box-ticking and becomes defensible engineering.

Defense in depth, not a single wall

No one control is "the security." The firewall will eventually let something through, a service will eventually have a bug, a credential will eventually leak; the point of layering accounts, sandboxing, MAC, patching, and auditing is that an attacker has to defeat several independent controls in sequence, and each layer buys time and noise for the next. When a control feels redundant with another, that redundancy is usually the design working, not waste.

Exercise

For each of these controls, name the threat from 12.1 it primarily answers: disabling password SSH login, mounting /tmp with noexec, enabling automatic security updates, and running a service under a confined systemd unit. Then say which single control, if you could keep only one on an internet-facing host, you would keep, and defend the choice in a sentence.

Chapter 13Applying a Baseline with the SCAP Security Guide

Hardening by hand does not scale and does not audit.

This chapter applies a named, machine-checkable baseline to the Grimoire Box, and confronts the fact that the baseline you get depends entirely on which family you are standing on. Where an authority is missing, the chapter says so and recommends a defensible course rather than pretending.

13.1 The SCAP Security Guide and OpenSCAP

The SCAP Security Guide (the open-source ComplianceAsCode project) is the connective tissue of Linux hardening. It ships machine-readable profiles (a DISA STIG profile, CIS profiles at Levels 1 and 2, PCI-DSS, the German BSI baseline, and others) together with the remediation to apply them, as Ansible and as Bash. The oscap tool scans a system against a profile and can generate a fix; the same content underlies the vendor compliance tooling. Learn this one toolchain and you can harden and audit any family it supports, which is most of them, including Fedora.

13.2 RHEL and AlmaLinux: the full stack

The Red Hat family is the easy case because it has every layer of authority at once. There is a DISA STIG (a U.S. Department of Defense configuration standard) for RHEL, a CIS Benchmark, and first-class SCAP content that implements both, all of which apply to AlmaLinux because it is binary-compatible. This is the concrete reason the book anchors its hardening here.

Standard · DISA RHEL 9 STIG: a named, versioned baseline

The DISA Security Technical Implementation Guide for Red Hat Enterprise Linux 9, current release v2r8 (April 2026), specifies several hundred configuration requirements at assigned severities, from SSH and authentication settings to audit rules and partition mount options. A RHEL 10 STIG followed and is now published as v1r1 (June 2026). Because AlmaLinux 10 is binary-compatible with RHEL 10, the RHEL STIG and its SCAP profile apply to it directly; this is what lets a free rebuild satisfy a federal baseline.DISA STIG for Red Hat Enterprise Linux 9, v2r8 (April 2026), and for Red Hat Enterprise Linux 10, v1r1 (June 2026); confirm the current release at the DoD Cyber Exchange, public.cyber.mil/stigs, which is the authoritative source. STIG revisions are frequent; pin the version in any audit artifact.

13.3 Debian: CIS-anchored, and what to do without a STIG

Debian is where the missing-authority problem appears, and it is worth meeting head on rather than discovering during an audit. There is no DISA STIG for Debian. That is a plain fact, not an oversight on your part: DISA simply does not publish one. What Debian does have is a CIS Benchmark and full SCAP coverage, which is a real, defensible baseline; it is just not a federal one.

So the recommended course, in order of how strict your obligation is. If you answer to general security best practice, harden Debian to the CIS Debian 13 Benchmark (Level 1 as a baseline, Level 2 where the workload justifies the friction) using the SCAP profile, and you are on solid, auditable ground. If you answer to a federal mandate that names "a STIG," you have two defensible options: run a Debian-family member that does have one (Ubuntu, see the next section), or apply CIS's STIG-mapped content, since the U.S. Department of Defense accepts CIS Benchmarks as an alternative where no STIG exists. What you must not do is leave Debian unhardened because "there's no STIG for it," or quietly apply a RHEL STIG's settings to a Debian box and call it compliant; the rules do not transfer cleanly and the audit will not credit them.

Standard · CIS Debian 13 Benchmark, and the DoD acceptance of CIS

The CIS Debian Linux 13 Benchmark (v1.0.0) is the authoritative consensus baseline for Debian and is implemented as a SCAP profile you can scan and remediate with oscap. Where a federal requirement names a STIG and none exists for the platform, DoD policy treats a CIS Benchmark as an acceptable alternative, and CIS publishes STIG-mapped profiles and hardened images to bridge the remaining gap.CIS Debian Linux 13 Benchmark v1.0.0; CIS Distribution-Independent Linux Benchmark v2.0.0 as a fallback where no per-distro benchmark fits. The DoD acceptance of CIS where no STIG exists is stated by CIS and attributed to the DoD Cloud Computing SRG; confirm the current SRG wording before citing it in an audit artifact, as this is the one load-bearing claim here not taken from a primary DoD document.

13.4 Ubuntu: the Debian-family system that has a STIG

This is exactly why the book covers Ubuntu rather than waving at it. Ubuntu has a DISA STIG (Canonical Ubuntu 24.04 LTS, current release v1r5, May 2026) and a CIS Benchmark, with SCAP content for both. For a shop that prefers the Debian world but lands a contract requiring STIG compliance, the answer is not to abandon what it knows for the Red Hat family; it is to standardize on Ubuntu LTS, where the same apt world it already runs carries a federal baseline. The cost is Ubuntu's particular defaults (snap, its own installer, AppArmor rather than SELinux); the benefit is a certifiable Debian-family path.

13.5 Arch: no certifiable baseline, stated plainly

Arch has neither a STIG nor a CIS Benchmark, and it cannot really have one: a rolling release has no fixed version to certify, and a baseline is a statement about a fixed configuration. The recommended course is correspondingly blunt. You can and should still harden an Arch host, using the Arch Wiki's security guidance and the CIS Distribution-Independent Linux Benchmark as the nearest portable yardstick, and the systemd and SSH hardening in this book applies unchanged. But if your environment requires demonstrable compliance against a named baseline, that requirement by itself is a reason not to run Arch there, and recognizing that early is part of choosing a family by its promise.

Lab 11 · Scan the Grimoire Box against a CIS profile

Goal: run a real OpenSCAP scan on AlmaLinux 10, read the report, and remediate one finding, so "compliance" stops being an abstraction.

# dnf install -y openscap-scanner scap-security-guide
# oscap xccdf eval --profile cis_server_l1 \
    --results scan.xml --report scan.html \
    /usr/share/xml/scap/ssg/content/ssg-almalinux10-ds.xml
[ ... rules evaluated, pass/fail tallied ... ]

Open scan.html, pick one failed rule, read its rationale and its fix, apply the fix, and re-scan to watch it pass. The exact profile name and content file are version-specific; list what your SSG package actually ships with oscap info rather than copying the names above. On Debian, the same lab runs with the Debian datastream and a CIS profile; note that no stig profile is offered there, which is section 13.3 made tangible.

Exercise

You are handed a host and told to "make it CIS Level 1." Name the one command that lists which profiles your installed SSG package actually ships, explain in a sentence why you scan and read the report before applying any remediation, and say what the absence of a stig profile on a Debian datastream tells you about that platform's available baselines.

Chapter 14Hardening SSH, Authentication, the Kernel, and Services

Applying a baseline in Chapter 13 does most of the work; this chapter covers the high-value hardening you should understand by hand, both because the reasoning matters and because some of it the tooling will not decide for you.

The aim is the handful of changes that buy the most security per unit of risk, with the why attached so you can defend each one in an audit.

14.1 Authentication: password quality and lockout

The accounts and PAM stack from Chapter 5 are where most authentication hardening lands. Two modules do the heavy lifting: pam_pwquality enforces password complexity and a minimum length, and pam_faillock locks an account after repeated failures, blunting brute force. The exact numbers are set by your baseline and differ between authorities (the DISA STIG, for instance, requires a 15-character minimum password length on RHEL, stricter than some CIS profiles), which is why you set them through the SCAP profile rather than inventing values. On the Red Hat family, make these changes through authselect so the tool that owns system-auth does not revert them.

14.2 The kernel: sysctl hardening

A set of kernel tunables, set through /etc/sysctl.d/, closes off information leaks and network tricks. The common ones: kernel.dmesg_restrict=1 and kernel.kptr_restrict=2 hide kernel pointers and logs from unprivileged users; fs.suid_dumpable=0 stops setuid programs from writing core dumps an attacker could mine; and a group of network settings (reverse-path filtering, ignoring ICMP redirects, logging "martian" packets) harden the host against spoofing. As always, the baseline supplies the canonical set.

# /etc/sysctl.d/90-hardening.conf  (illustrative; take the canonical set from the SCAP profile)
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.suid_dumpable = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
# sysctl --system  # apply all sysctl.d drop-ins now
Caution

Network sysctl hardening can break legitimate behavior: strict reverse-path filtering disrupts asymmetric routing, and disabling forwarding breaks a host that is meant to route or run containers. Apply the set the baseline specifies, then test the workload, rather than pasting a maximal list from a blog. A host that is perfectly hardened and cannot do its job is not hardened, it is broken.

14.3 Services: sandbox and reduce

Two complementary moves shrink the system's attack surface. First, tighten the systemd sandboxing from Section 7.5 on every exposed service to the strictest set it tolerates, since a confined service is a smaller prize. Second, remove what you do not run: every installed package and enabled service is attack surface, so uninstall unused software and disable unneeded units. The baseline checks for specific offenders (legacy services, unnecessary network daemons); the principle generalizes to everything.

Best practice

Harden through the SCAP profile first, then hand-tune the few things it does not cover, and verify the result by re-scanning rather than by eyeballing. The profile is peer-reviewed and re-derived as standards change; your hand-edits are not, so keep them minimal and documented. The goal is a system whose security posture you can regenerate from version-controlled content, not one held together by remembered tweaks.

Lab 12 · Kernel and auth hardening, then verify

Goal: apply a sysctl hardening drop-in and confirm it took effect on both families, and confirm account lockout is active.

# # add the drop-in from 14.2, then:
# sysctl --system
# sysctl kernel.dmesg_restrict fs.suid_dumpable  # confirm the live values
# # trigger a few failed logins for a test user, then:
# faillock --user testuser  # see the recorded failures / lock state

Do this on Debian and AlmaLinux and note that the sysctl mechanism is identical; only the authentication tooling differs (authselect on the Red Hat family versus editing the common-* stacks on Debian). Re-scan with the Chapter 13 profile to confirm the findings these settings address now pass.

Exercise

You paste a "maximum security" list of forty sysctl settings from a blog and the host's containers stop networking. Name the most likely category of setting responsible, and state the discipline from this chapter that would have prevented the outage.

Chapter 15Mandatory Access Control: SELinux and AppArmor Compared

Everything so far assumes a service behaves.

Mandatory access control assumes it does not: it confines a process by kernel-enforced policy so that even a fully compromised, root-running service can only touch what its policy allows. The two families take different routes to the same goal, and this chapter teaches enough of each to operate it without breaking it. The deep dive into writing SELinux policy is its own Grimoire volume.

15.1 Why discretionary permissions are not enough

Ordinary Linux permissions are discretionary (DAC): the owner of a file decides who can read it, and a process running as root can do anything. That means a compromised root service has the run of the machine. Mandatory access control (MAC) adds a second, non-negotiable layer: a system-wide policy, enforced by the kernel, that even root cannot override, confining each service to the files, ports, and capabilities its job requires. It is the difference between a compromised web server and a compromised host.

15.2 SELinux on the Red Hat family

The Red Hat family uses SELinux, which labels every process and file with a type and enforces rules about which types may interact (type enforcement). The default targeted policy confines the network-facing services that matter and leaves the rest alone; the system runs in enforcing mode. You check it with sestatus and getenforce, and you adapt policy without writing any by flipping booleans and fixing file labels. Authoring policy is deep water, and it is exactly what the SELinux volume of this series covers; here you need to read its state and not break it.

# sestatus  # mode, policy, and whether enforcing
# getsebool -a | head # the booleans that tune policy without editing it

15.3 AppArmor on Debian and Ubuntu

Debian and Ubuntu use AppArmor, which confines programs by path rather than by label: a profile lists the files and capabilities a given executable may use. Profiles live in /etc/apparmor.d/, can run in enforce mode (violations blocked) or complain mode (violations logged only, useful while developing a profile), and you inspect them with aa-status. Path-based profiles are easier to read and write than SELinux types, at the cost of being less comprehensive; both are real, kernel-enforced MAC.

15.4 Two routes, one control, and the advice everyone ignores

Label-based and path-based MAC have different strengths (SELinux is more thorough and more complex; AppArmor is simpler and more legible), but for this book's purposes they answer the same control: confine the service. Arch ships neither by default, which is one more entry in its "you assemble it yourself" ledger. The most important operational lesson is the same on both families and is the single most common piece of bad advice on the internet.

Standard · DISA STIG: enforcing MAC is required, not optional

The DISA RHEL 9 STIG requires SELinux to be in enforcing mode; a system that is permissive or disabled is a Category I (high severity) finding (RHEL-09-431010); the RHEL 10 STIG keeps the requirement but rates the equivalent control Category II (RHEL-10-700420), so confirm the severity against the generation you are audited under. The Ubuntu STIG and the CIS Benchmarks require AppArmor to be installed and enabled on the Debian family. The near-universal bad advice, "just run setenforce 0" or "disable AppArmor" to make something work, takes a passing system straight to a STIG finding (the most severe class, Category I, on RHEL 9; Category II on RHEL 10). The correct move is to fix the label or boolean (SELinux) or the profile (AppArmor) so the service works while confined.DISA RHEL 9 STIG, finding RHEL-09-431010 (SELinux enforcing, CAT I), and DISA RHEL 10 STIG, finding RHEL-10-700420 (CAT II); Canonical Ubuntu 24.04 STIG and CIS Benchmarks for AppArmor enablement. Verify current finding identifiers in the SCAP profile (Chapter 13); the deep treatment of SELinux policy is the dedicated SELinux volume of this series.

Caution

Disabling MAC to fix a problem trades a five-minute diagnosis for a permanent, severe security regression, and it is the first thing an auditor checks. When a service misbehaves under SELinux or AppArmor, read the denial (the audit log in Chapter 18 shows exactly what was blocked) and grant that one thing. Reaching for setenforce 0 is the Linux equivalent of unplugging the smoke detector.

Lab 13 · Read the MAC state on both families

Goal: confirm the Grimoire Box is confined, the right way, on each family: enforcing SELinux on AlmaLinux and an active AppArmor on Debian.

# AlmaLinux
# sestatus && getenforce  # expect: enforcing
# Debian
# aa-status  # expect: module loaded, profiles in enforce mode

Neither should be disabled. If either is, that is your first finding to fix, not a convenience to accept. Leave the deep policy work to the SELinux volume; the operating skill here is recognizing a confined system and keeping it that way.

Exercise

A service fails to read its data directory and a forum post tells you to run setenforce 0. Explain in two sentences why that is the wrong fix, what severity of audit finding it creates on a STIG-bound RHEL host, and what you would do instead.

Chapter 16The Cross-Family Standards Crosswalk

A hardened host usually has to answer to more than one authority at once: a DISA STIG, a CIS Benchmark, and a set of NIST SP 800-53 controls can all apply to the same machine.

The good news is that they mostly describe the same settings in different vocabularies, so one configuration satisfies all of them, and a crosswalk is the table that proves it. This chapter teaches how to read and maintain that table faithfully, which means deriving it from machine-readable content rather than transcribing identifiers by hand.

16.1 One configuration, several vocabularies

The STIG, CIS, and NIST 800-53 are not competing checklists so much as three views of the same security goals. "Disable root SSH login" is one setting; the STIG calls it a finding, CIS calls it a benchmark item, and NIST 800-53 places it under access-control and least-privilege controls. The crosswalk lines these up row by row so that when an auditor asks "how do you satisfy AC-6," you can point at the exact setting and the exact STIG and CIS items that implement it, all already configured by the chapters of this book.

16.2 Derive it, do not transcribe it

The single most important discipline here is to treat the crosswalk as generated, not hand-written. The SCAP Security Guide content from Chapter 13 already carries, for every rule, its STIG finding identifier, its CIS section, and its NIST 800-53 control references, as machine-readable metadata. So the authoritative crosswalk is produced from that content, not typed from memory, because typed identifiers rot: STIG findings and CIS sections renumber between revisions, and a transcribed table is wrong the day a standard updates.

Standard · The SCAP Security Guide is the mapping authority

ComplianceAsCode / the SCAP Security Guide encodes the control mappings directly in its rules, which is why an OpenSCAP report can show, per rule, the STIG and CIS and NIST references it satisfies. Use that content as the source of truth for the crosswalk; it is re-derived as the upstream standards change, so a crosswalk generated from it stays correct across revisions in a way a hand-maintained spreadsheet never does.SCAP Security Guide / ComplianceAsCode (github.com/ComplianceAsCode/content); NIST SP 800-53 Rev 5 for the control catalog; the per-distro DISA STIG and CIS Benchmark for the finding and section identifiers. Every specific identifier in the table below must be confirmed against the current content, not this page.

16.3 Reading the crosswalk

An extract makes the shape concrete. The NIST 800-53 control families are stable enough to name with confidence; the STIG and CIS identifiers are version-specific and are shown here as the kind of value that must be confirmed in the current SCAP profile, not as gospel.

Control areaWhere this book sets itNIST SP 800-53STIG / CIS (verify in the current SSG)
Mandatory access control enforcingCh 15AC-3, AC-6STIG RHEL-09-431010 (CAT I, RHEL 9) / RHEL-10-700420 (CAT II, RHEL 10); CIS MAC section
Root SSH login disabledCh 9AC-6, IA-2STIG and CIS SSH section (verify item numbers)
Host firewall, default-denyCh 10SC-7CIS host-firewall section (verify)
Password length and lockoutCh 5, Ch 14IA-5, AC-7STIG (15-char min on RHEL); CIS pwquality (verify)
Audit logging enabledCh 13, 18AU-2, AU-12STIG and CIS auditd section (verify)
Automatic security updatesCh 4SI-2CIS patch-management section (verify)

The full version of this table, expanded across the families and with every identifier confirmed against the current content, is Appendix B; it is built from the SCAP content rather than typed, for the reasons in 16.2.

16.4 Keeping it true

Because the identifiers move, the crosswalk needs a maintenance habit, not a one-time build. When you upgrade to a new SCAP Security Guide release (which tracks new STIG and CIS revisions), regenerate the crosswalk from the new content and diff it against the old; the diff is your changelog of what the standards now require. This is the same "verify against the primary source" discipline the rest of the book follows, applied to compliance: the machine-readable content is the primary source, and the human-readable table is a rendering of it that you refresh rather than edit.

Lab 14 · Generate a mapping, do not type one

Goal: produce a real rule-to-standard mapping from the SCAP content on AlmaLinux 10, so you see the crosswalk come out of the tooling rather than out of a person.

# oscap xccdf eval --profile stig --results r.xml --report r.html \
    /usr/share/xml/scap/ssg/content/ssg-almalinux10-ds.xml
# # open r.html and pick one rule; it lists the STIG/CIS/NIST references it satisfies

Confirm that the references the report shows for a rule (its STIG identifier and NIST controls) match the corresponding row of 16.3, and note any that have renumbered since this page was written. That divergence is exactly why the crosswalk is generated, not memorized.

Exercise

An auditor asks how the host satisfies NIST 800-53 control AC-6 (least privilege). Name two settings from this book that map to it, and explain in one sentence why you would answer from a generated crosswalk rather than from a table a previous administrator typed by hand last year.

Part V Operating in Production

A hardened host that nobody can restore, observe, or reproduce is not in production, it is on borrowed time. This part covers the operational afterlife: backups you have actually tested, the ability to see what a sick system is doing, running containers as first-class services, and rebuilding any host from code.

Chapter 17Backup, Restore, and Tested Recovery

A hardened, automated host is still one bad command or one dead disk away from gone, and the thing that decides whether that is a shrug or a catastrophe is whether you have a backup you have actually restored from.

This chapter separates what to back up from what to rebuild, covers the strategies that work, and insists on the one practice everyone skips: testing the restore.

17.1 Back up data, rebuild the system

Not everything deserves a backup, and conflating the two makes backups bigger and restores slower. Split the host in two. The data is irreplaceable and must be backed up: the Grimoire Box's Git repositories in /srv/git, any databases, and the configuration in /etc that represents real decisions. The system (the OS, the packages, the base configuration) is reproducible: you can rebuild it from the install and the Ansible playbook in Chapter 20, so it does not need a traditional backup. Backing up the data and being able to regenerate the system is faster and more reliable than imaging whole disks.

17.2 Strategies that hold up

Three approaches cover most needs. File-level backup with a tool like restic or BorgBackup gives deduplicated, encrypted, incremental copies of the data directories, which is the right default for the Grimoire Box. Snapshots (LVM snapshots from Chapter 6, or Btrfs snapshots on AlmaLinux) give an instant, point-in-time copy that is excellent for taking a consistent backup of a busy volume or a pre-upgrade safety net, but a snapshot on the same disk is not a backup, it is a convenience. The discipline that ties it together is the 3-2-1 rule: at least three copies, on two kinds of media, with one off the host entirely.

Caution

A backup on the same machine, or the same disk, as the data is not a backup; it dies with the host. A snapshot is not a backup either, for the same reason. The copy that saves you is the one somewhere else: another machine, another building, another account. If a single rm -rf or a single failed disk can destroy both the data and its "backup," you do not have one.

17.3 The restore drill

This is the part that separates real backups from hopeful ones. A backup you have never restored is an untested assumption: the archive may be corrupt, the encryption key may be lost, the procedure may have a missing step, and you will discover all of this at the worst possible moment. So restore on a schedule, to a scratch location, and compare against the original. A restore you have rehearsed is a procedure; a restore you have not is a gamble with your data as the stake.

Best practice

Put a calendar reminder to do a test restore on a cadence (monthly is reasonable for important data), restoring to a throwaway directory and diffing against live. Backups are also one of the places the compliance baselines are comparatively quiet, leaning on contingency-planning controls rather than prescribing a tool, so this is genuinely a best-practice judgement rather than a checkbox: the standard cannot test your restore for you, only you can.

17.4 The Grimoire Box backup

Concretely: a systemd timer from Chapter 11 runs a nightly restic backup of /srv/git and /etc to an off-host repository, and a monthly reminder triggers a test restore. Because the data lives on its own LVM volume (Chapter 6), the backup scope is one clean, well-defined target rather than a guess about what matters scattered across the root filesystem. That earlier design decision is what makes this chapter simple.

Lab 15 · Back up and actually restore

Goal: back up the Grimoire Box data to an off-host target and prove the restore works, on both families (the tooling is identical).

# restic -r sftp:backup-host:/srv/backups/grimoire init
# restic -r sftp:backup-host:/srv/backups/grimoire backup /srv/git /etc
# # now the part everyone skips: restore to a scratch dir and compare
# restic -r sftp:backup-host:/srv/backups/grimoire restore latest --target /tmp/restore-test
# diff -r /srv/git /tmp/restore-test/srv/git && echo "RESTORE VERIFIED"

If the diff is clean, you have a backup; if you skipped it, you have a hope. Schedule the backup as a timer and the restore test as a reminder.

Exercise

A colleague proudly shows you a nightly LVM snapshot of the data volume and calls it the backup. Give the two distinct reasons that is not a backup, and name the one test that would tell them whether their actual off-host copies can be recovered from.

Chapter 18Observability and Troubleshooting

When a host misbehaves at 2 a.m., the difference between a ten-minute fix and a two-hour flail is having a method instead of a guess.

This chapter gives you both the small set of tools that diagnose almost everything (all present on every family by default) and an order to use them in, so you converge on the cause instead of poking at symptoms.

18.1 Start at the journal

The first question is almost always "what does the service say it is doing," and the journal from Chapter 7 answers it. systemctl status grimoire-git shows the unit's state and last log lines; journalctl -u grimoire-git -e reads its full log; journalctl -p err -b shows this boot's errors across the whole system; and journalctl -k shows kernel messages. If you enabled a persistent journal (the gotcha from Section 7.4), you can also read across reboots, which matters when a host has already crashed and come back.

18.2 The triage tools, and the cause they each find

Most incidents are one of four things, and one tool each finds them. Disk full is the single most common cause of bizarre, unrelated failures, and df -h (and du -sh * to find the culprit) catches it in seconds; a full / or /var breaks logging, databases, and services in ways that look like everything is wrong at once. Out of memory shows up in free -h and, when the kernel's OOM killer has shot a process, in dmesg and the journal. CPU saturation is visible in top or htop. And network issues yield to ss -tlnp (what is listening), ip addr (do we have an address), and a name lookup (Chapter 8). Learn these six and you can localize most problems to a subsystem fast.

Best practice

Check disk space and the journal first, every time, before theorizing. A startling fraction of "the database is corrupt" and "the service randomly died" incidents are simply a full filesystem, and df -h rules it in or out in one second. Building the reflex to check the cheap, common causes before the expensive, exotic ones is most of what makes an experienced operator fast.

18.3 A method, not a flail

Put it in order so you are systematic under pressure: read the service's journal; check whether a resource is exhausted (disk, then memory, then CPU); check the network if it is a connectivity symptom; and check permissions and mandatory-access-control denials (Chapter 15) if it is an "access denied" symptom, since an SELinux or AppArmor denial looks exactly like a bug until you read the audit log. Each step either finds the cause or rules out a whole category, which is how you converge instead of wander.

When the kernel kills your service

If a service vanishes without logging an error of its own, suspect the OOM killer: when memory is exhausted the kernel terminates a process to survive, and it records which one in dmesg and the journal. This ties directly back to the resource limits in Chapter 11: a MemoryMax on the service confines the damage to that service instead of letting it drive the whole host into the OOM killer's sights.

18.4 The audit log: what auditd records, and reading a denial

The "access denied" branch of that method has its own log, separate from the journal, and it is usually where the answer is. The Linux kernel's audit subsystem records security-relevant events (logins, privilege use, file and syscall access, and policy denials) through a userspace daemon, auditd, which writes them to /var/log/audit/audit.log. It is enabled by default on the Red Hat family; on Debian the auditd package is installed and enabled as part of hardening rather than out of the box. You rarely write audit rules by hand, because the rules a STIG or CIS Benchmark requires are exactly what the SCAP profile from Chapter 13 lays down in /etc/audit/rules.d/. That is the auditd half of "applying the baseline," which is why the crosswalk maps audit logging both to the chapter that installs the rules and to this one, where you read them.

The operating skill is the reading. Two tools turn the raw log into answers: ausearch filters it and aureport summarizes it. The single most useful query ties straight back to Chapter 15: when a service fails in a way that looks like a bug but is really SELinux or AppArmor blocking it, the denial is an AVC record here, and reading it tells you exactly what to allow instead of reaching for setenforce 0.

# ausearch -m AVC -ts recent  # MAC denials in the last 10 minutes
# ausearch -m AVC -ts today  # every policy denial today
# aureport  # an overall summary of audited events

On the Red Hat family, audit2why reads a denial and explains in plain terms which rule blocked it; on Debian, an AppArmor denial lands in the same log and is turned into a profile adjustment with aa-logprof. The depth of audit-rule authoring (field syntax, file watches, syscall filters) is a security subsystem in its own right; what every administrator needs is to know the audit log exists, that the baseline populates it, and that an unexplained "permission denied" is one ausearch -m AVC away from a diagnosis rather than a disabled security module.

Lab 16 · Diagnose a planted failure

Goal: practice the method on a known fault so it is automatic on an unknown one, on both families.

# # fill a scratch filesystem to simulate a full disk, then observe the fallout:
# df -h  # step 1: is a filesystem full?
# journalctl -p err -b  # step 2: what is erroring
# systemctl --failed  # step 3: which units failed

Walk the steps in order rather than jumping to the service you suspect. Note that every command here exists and behaves identically on Debian and AlmaLinux; troubleshooting is one of the most portable skills in the book.

Exercise

A web service "randomly dies" every few days with nothing in its own logs. Name the two cheap checks you run first, name the kernel mechanism that would kill a process silently from the service's point of view, and say where it records what it did.

Chapter 19Containers as Managed Services: Podman and systemd

Enough container fluency to run one as a hardened systemd service, without turning the book into an orchestration manual.

Containers earn their place in this book for one reason: run as a rootless systemd service, a container is a cleanly packaged, well-confined way to run a workload, and it slots directly into everything you already learned about systemd. We use Podman, run rootless by default, and wire containers in as systemd units with Quadlet. Orchestration across many hosts (Kubernetes) is a different subject and a companion's job; this is the single-host story, done well.

19.1 Podman, and why daemonless and rootless

Podman runs containers without a central daemon and, crucially, without root: an ordinary user can run containers, and the container's "root" is mapped through user namespaces to an unprivileged UID on the host. Its command line mirrors Docker's (podman run, podman ps, podman build), so existing knowledge transfers, but the security posture is better out of the box because there is no root-owned daemon to compromise. Podman is the default container engine on the Red Hat family and is fully available on Debian and Ubuntu.

19.2 The rootless security model

This is the payoff and it connects straight back to Section 7.6. A rootless container runs under a normal user account, supervised by that user's systemd instance, and a breakout from the container lands as an unprivileged user on the host rather than as root. Combined with the systemd sandboxing from Section 7.5, which applies to container services too, this is genuine defense in depth: the attacker must escape the container, then escalate from an unprivileged account, then defeat the host hardening, instead of starting at root.

Standard · NIST SP 800-190: container security

NIST SP 800-190, the Application Container Security Guide, frames the risks of containerized workloads (image provenance, runtime isolation, least privilege) and is the authoritative reference where this book touches containers. Its guidance lines up with the rootless, confined, systemd-managed approach here: minimize the container's privileges, isolate it from the host, and manage it as a supervised service rather than a detached process.NIST SP 800-190, Application Container Security Guide, csrc.nist.gov. It is guidance rather than a pass/fail benchmark; the CIS Benchmarks additionally publish container-specific content (for example for Docker) that applies in part to Podman. Confirm specifics against the current documents.

19.3 Quadlet: containers as systemd units

You do not hand-write unit files for containers, and you no longer use the deprecated podman generate systemd. Instead, Quadlet (merged into Podman 4.4) lets you describe a container declaratively in a .container file, and systemd generates the service. Drop it in ~/.config/containers/systemd/ for a rootless user service or /etc/containers/systemd/ for a system one, reload, and you have a managed, auto-restarting, logged service.

There is no official upstream image for the bare git daemon the Grimoire Box runs, so build the running example's own; that is itself the point, because a container image is just the service from Section 7.1 packaged to run anywhere. A short Containerfile does it:

# Containerfile  (build it with: podman build -t grimoire-git .)
FROM docker.io/library/debian:trixie-slim
RUN apt-get update && apt-get install -y --no-install-recommends git \
    && rm -rf /var/lib/apt/lists/*
EXPOSE 9418
ENTRYPOINT ["git", "daemon", "--reuseaddr", "--base-path=/srv/git", "--export-all", "/srv/git"]

That produces localhost/grimoire-git:latest, the image the Quadlet below runs. The .container file then points systemd at it, binding the same /srv/git data volume from Chapter 6 so the rootless service serves the real repositories rather than an empty directory. One detail has to be right: rootless Podman needs a user with subordinate UID/GID ranges (in /etc/subuid and /etc/subgid) and a login-managed user instance, and the git account from Section 5.1 is a nologin system account with neither. So the rootless incarnation runs under a dedicated unprivileged login user created for it (the lab calls it gitsvc), which gets subordinate ranges and a user manager and is granted read access to /srv/git, rather than the nologin git service account the Section 7.1 system unit uses or a human admin's login. This is the alternative to that system unit, not a second copy of the data:

# ~/.config/containers/systemd/grimoire-git.container
[Unit]
Description=Grimoire Box Git service (rootless container)

[Container]
Image=localhost/grimoire-git:latest
PublishPort=9418:9418
Volume=/srv/git:/srv/git:Z

[Service]
NoNewPrivileges=true  # Quadlet passes [Service] through: add the 7.5 sandboxing the container should carry

[Install]
WantedBy=default.target
A full Git service, if you want one

The minimal image above keeps the running example's git daemon intact, which is all the Grimoire Box needs. If you would rather run a full, multi-user Git service with a web UI, the credible off-the-shelf choice is Gitea (docker.io/gitea/gitea), a maintained, self-hosted Git service distributed as a container; its community fork Forgejo is equivalent. Point Image= at it instead and adjust the published ports, since Gitea serves HTTP and SSH rather than the git:// daemon protocol on 9418. The technique (Quadlet, lingering, a confined rootless service) is identical whichever image you run.

Caution

Two rootless gotchas, both met earlier. First, lingering: a rootless container is a user service, so without loginctl enable-linger (Section 7.6) it dies at logout and never starts at boot. Second, low ports: an unprivileged user cannot bind ports below 1024 without extra configuration, so a rootless container publishing port 80 needs either a high port plus a proxy or an explicit sysctl grant. Neither is a reason to fall back to running everything as root; they are the small price of the better posture.

19.4 Where this stops

Running one container, or a few, as managed services on a host is in scope and complete here. Orchestrating containers across a cluster (scheduling, service discovery, rolling updates) is Kubernetes, and it is a large enough subject to be its own volume rather than a half-chapter; this book points there rather than pretending to cover it. The single-host skills transfer, but the orchestration layer is deliberately out of scope, the same boundary the introduction drew.

Lab 17 · A rootless container service that survives logout

Goal: run the Grimoire Box service as a rootless Quadlet container under a dedicated unprivileged login user (gitsvc; the nologin git system account cannot run one, as 19.3 explains), with lingering, on both families.

# useradd -m gitsvc  # a dedicated unprivileged login user (gets subuid/subgid automatically)
# usermod -aG git gitsvc  # read access to the git-owned /srv/git
# loginctl enable-linger gitsvc  # its user manager starts at boot and survives logout
# machinectl shell [email protected]  # enter gitsvc's session to run the user-level commands below
$ podman build -t grimoire-git .  # as gitsvc: build localhost/grimoire-git from the Containerfile in 19.3
$ # place the .container file from 19.3 in ~/.config/containers/systemd/
$ systemctl --user daemon-reload
$ systemctl --user start grimoire-git
$ podman ps  # confirm it is running, rootless, in gitsvc's session

Log out and back in, or reboot, and confirm the service is still up, which proves lingering did its job. Podman, Quadlet, and the commands are identical on Debian and AlmaLinux; this is a portable skill.

Exercise

You deploy a rootless container over SSH, it runs, and it is gone after you disconnect. Name the one command that fixes it and why. Then explain why a breakout from a rootless container is less severe than from a root-run one.

Chapter 20Automation as the Spine: Ansible

Everything this book did by hand, it should be able to do from code, the same way every time, on every host.

That is configuration management, and it is also the real answer to "how does single-host administration scale": not by magic orchestration, but by making each host a reproducible artifact you can rebuild and multiply. We use Ansible, and the comparative knowledge from the whole book is exactly what lets you write playbooks that work across the families.

20.1 Why automate, and what idempotence means

A host configured by hand is a snowflake: undocumented, unreproducible, and slightly different from its siblings in ways nobody remembers. Automation replaces the hand with code, so the configuration is written down, version-controlled, and identical across hosts. The core discipline is idempotence: a good automation task describes the desired state ("git is installed," "this service is enabled") so that running it once or running it ten times leaves the same result, rather than describing steps that break if repeated. This is what lets you re-run the whole configuration any time to correct drift.

20.2 Ansible, briefly

Ansible is agentless: it configures hosts over SSH (which you already hardened in Chapter 9), with nothing to install on the targets. You describe an inventory of hosts and write playbooks of tasks, each task invoking a module (package, service, copy, user) that knows how to reach a desired state idempotently. Related tasks group into reusable roles. It is YAML, it reads like a checklist, and it runs the same from your laptop against one host or a thousand.

20.3 One playbook, several families

Here the whole book pays off. Ansible abstracts some differences for you (the package module calls apt or dnf as appropriate, the service module drives systemd everywhere), but it cannot abstract the differences that are genuinely semantic: package names differ, the sudo group differs, the firewall front end differs, the MAC system differs. So a cross-family playbook branches on ansible_os_family for exactly the divergent points this book taught you to recognize, and shares everything else. Knowing which parts diverge, and why, is precisely the comparative understanding the rest of the volume built.

# a task that works on both families by branching only where it must
- name: Install git
  package:
    name: git
    state: present  # the package module picks apt or dnf automatically

- name: Add admin to the right sudo group
  user:
    name: alice
    groups: "{{ 'sudo' if ansible_os_family == 'Debian' else 'wheel' }}"
    append: true  # the one divergence, handled explicitly
Best practice

Put the playbook in version control and make it the source of truth: to change a host, change the code and re-run, never hand-edit the box and hope to remember. A playbook that has drifted from reality is worse than none, because it lies about the state of the fleet. The payoff is real: patching, hardening re-application, and rebuilding a lost host all become "run the playbook," which is how a single administrator credibly manages many machines.

20.4 The real ceiling of "scaling"

This is as far as this volume takes scaling, and it says so plainly. Single-host administration scales by reproducibility (golden images, playbooks, fleet-wide patch runs), not by the application-clustering and orchestration that belong to other subjects. Turning the Grimoire Box into a role that rebuilds it from a blank VM is the capstone's final move (Chapter 23); load balancing, distributed state, and Kubernetes are deliberately beyond the boundary, pointed to rather than half-taught.

Lab 18 · One playbook, both families

Goal: write a minimal playbook that installs git and creates the service account on Debian 13 and AlmaLinux 10 from one file, branching only where the families truly differ.

$ ansible -i inventory all -m ping  # confirm SSH reach to both hosts
$ ansible-playbook -i inventory grimoire.yml  # apply the tasks from 20.3
$ ansible-playbook -i inventory grimoire.yml  # run again: idempotent, nothing changes

Run the playbook twice and confirm the second run reports no changes; that is idempotence, and it is what makes the playbook safe to re-run forever. Note that the only family-specific line was the sudo group, exactly the divergence Chapter 5 taught you to expect.

Exercise

Explain why a playbook task that says "append this line to a config file" is a worse idea than one that says "ensure the file has this content," in terms of idempotence. Then name two points in this book where a cross-family playbook genuinely must branch on the distribution family.

Part VI Legacy, Migration, and Upgrades

Most administration is not greenfield. You inherit a box nobody documented, on a release that went end-of-life two years ago, and you have to make it safe without breaking the thing it runs. This part is the one the happy-path tutorials skip, and it is where the families' upgrade philosophies finally pay off or punish.

Chapter 21Inheriting a System: Assessing an Unknown or EOL Box

Most administration is not building new systems; it is taking over old ones.

You inherit a box nobody documented, on a release that may be years past end of life, running something the business depends on, and your job is to make it safe without breaking it. This chapter is the disciplined first hour: assess before you act, snapshot before you change, and decide between patching, upgrading, and rebuilding from evidence rather than instinct.

21.1 Do no harm: assess before you touch

The strongest instinct with a neglected box, to start fixing things, is the one to resist. A production system you do not understand can depend on the very misconfiguration you are about to "fix," and a service can be load-bearing in ways no one remembers. So the first hour is read-only: observe, inventory, and above all take a recoverable snapshot before you change a single setting, so that every later decision has an undo.

Caution

Snapshot or image the system before your first change, not your first risky change. The whole point of an inherited box is that you do not know what is load-bearing, which means you cannot know which change is the dangerous one until after it breaks something. A snapshot taken before you began is the difference between "restore and rethink" and "explain to the business why the thing stopped working."

21.2 What do I have, and how far out of support

Start with identity. cat /etc/os-release and uname -r tell you the distribution, version, and kernel; then the critical question is how far past support it is, because an end-of-life system receives no security updates and every day raises the risk. The canonical example is exactly the inherited Grimoire Box: a CentOS 7 host, a distribution that reached end of life on 30 June 2024 and now accumulates unpatched vulnerabilities with no fix coming. Knowing the support status turns a vague unease into a concrete clock.

21.3 What does it run, and who depends on it

Next, inventory what the box actually does, because the documentation (if any) will be wrong. The read-only tools from the rest of the book do the work: ss -tlnp shows every listening service and the process behind it, systemctl list-units --type=service --state=running shows what is active, ps aux shows the full picture, and the cron tables and timers (crontab -l, systemctl list-timers) reveal scheduled work. Look in /srv, /opt, and /var/www for what is served, and check who has been logging in. The goal is a written inventory of services, dependencies, and data, so the decision in 21.5 is informed.

21.4 Is it already wrong, or already breached

While inventorying, note the obvious red flags, because an inherited box is often misconfigured and sometimes compromised. Is mandatory access control disabled (Chapter 15), is there no firewall (Chapter 10), are there unexpected listening ports, unknown user accounts, world-writable files in odd places, or services nobody can explain? You are not doing a full forensic investigation, but a quick pass against the things this book taught you to expect will surface most of what makes an old box dangerous, and it feeds directly into whether you can trust the system at all.

21.5 Decide: patch, upgrade, or rebuild

With the evidence in hand, choose. If the system is supported and merely behind, patch in place and bring it under the automation and hardening of the rest of the book. If it is supported but on an older major, plan an upgrade (Chapter 22). If it is end of life, the realistic answer is usually rebuild and migrate: stand up a clean, current, hardened host (the capstone in Chapter 23), move the data and the service onto it, and retire the old box, because an EOL system cannot be made safe by patching alone. For the CentOS 7 Grimoire Box, rebuilding onto AlmaLinux is both cleaner and faster than nursing the old one forward, though Chapter 22 covers the in-place migration path when a rebuild is not possible.

Best practice

Write the inventory down as you go, even if it is a scratch file: distribution and support status, every listening service and who owns it, the data locations, the scheduled jobs, and the red flags. That document is what turns a panicky "I guess we can't touch it" into a plan, and it is the thing your successor will wish you had left them, because you are currently living the alternative.

Lab 19 · A read-only assessment of an unknown box

Goal: run a safe, read-only assessment of a system you treat as inherited (use a CentOS 7 or old Debian VM), producing a one-page inventory without changing anything.

# cat /etc/os-release; uname -r  # what and how old
# ss -tlnp  # what is listening, and the process
# systemctl list-units --type=service --state=running
# systemctl list-timers; for u in $(ls /var/spool/cron 2>/dev/null); do crontab -l -u "$u"; done
# getenforce 2>/dev/null; nft list ruleset 2>/dev/null | head  # MAC and firewall posture

Take a snapshot first, change nothing, and write down what you found and how far past support the system is. Then decide, on paper, between patch, upgrade, and rebuild, and justify it from the inventory.

Exercise

You inherit a CentOS 7 server still in production. State its support status as a fact, give the first action you take before any change, and explain in two sentences why "just keep patching it" is not a safe long-term plan for an end-of-life distribution.

Chapter 22Two Upgrade Philosophies: leapp and Debian Stepwise Dist-Upgrade

Most of what you do to a system over its life is not install it; it is move it forward without breaking it. A major-version upgrade is the riskiest routine thing an administrator does, and it is the one place the families' philosophies have direct operational consequences: the Red Hat family hands you a single supported tool that rewrites the system in place, and the Debian family hands you a disciplined, documented walk from one release to the next.

This chapter does both on the Grimoire Box, including the end-of-life version of it you inherit in Chapter 21, and it is blunt about the one rule that makes either survivable.

22.1 What a major upgrade is, and why it bites

A minor update (AlmaLinux 9.5 to 9.6, Debian 12.7 to 12.8) is routine: same kernel series, same libraries, same defaults, applied continuously. A major upgrade (8 to 9, 12 to 13) changes the kernel, the compiler and core libraries, configuration formats, and dozens of defaults all at once. The danger is rarely the upgrade tool itself; it is the accumulated drift on a system that has been running for years, the third-party repository someone added in 2021, the config file hand-edited and forgotten, the service that only worked because of a default that is about to change. The tooling is good. The system you are pointing it at is the risk.

22.2 The Red Hat family: leapp, one major at a time

Red Hat's supported in-place upgrade is leapp. You run leapp preupgrade, which produces a report of inhibitors (hard blockers) and warnings; you work through them; then leapp upgrade stages the transaction and a reboot boots a special upgrade environment that performs it, finishing with a SELinux relabel on first boot. leapp moves one major version per run: 8 to 9, then 9 to 10. You cannot skip a major.

# RHEL/AlmaLinux, one major at a time
# dnf install -y leapp-upgrade
# leapp preupgrade  # produces /var/log/leapp/leapp-report.txt
# # resolve every inhibitor in the report first
# leapp upgrade
# reboot  # the upgrade runs in a special boot, then relabels

For CentOS, which has no native path forward, the AlmaLinux ELevate project extends leapp with cross-distribution migration data so you can move from CentOS onto AlmaLinux. ELevate is also one step at a time, so an old CentOS 7 box does not reach AlmaLinux 10 in a single jump; it climbs a staircase: CentOS 7 to AlmaLinux 8, then 8 to 9, then 9 to 10. The inherited Grimoire Box, last touched on CentOS 7, is exactly this case.

# CentOS 7 -> AlmaLinux 8, the first step of the staircase (ELevate)
# yum install -y http://repo.almalinux.org/elevate/elevate-release-latest-el7.noarch.rpm
# yum install -y leapp-upgrade leapp-data-almalinux
# leapp preupgrade
# leapp upgrade
# reboot
# then repeat 8 -> 9 and 9 -> 10 with the matching ELevate steps
Standard · The supported path is the vendor's path

For the Red Hat family the only supported in-place major upgrade is leapp; a hand-rolled dnf distro-sync against the next release's repositories is not supported and routinely breaks. Red Hat documents the procedure and the supported version pairs (8 to 9, 9 to 10) in its Upgrading guides. CentOS Linux is end of life and unsupported: CentOS Linux 8 reached end of life on 31 December 2021 and CentOS Linux 7 on 30 June 2024, which is why the inherited box is a migration target, not a patch target.Red Hat, "Upgrading from RHEL 9 to RHEL 10" and "Upgrading from RHEL 8 to RHEL 9," docs.redhat.com (the authoritative procedure and supported-path matrix; confirm the current pairs there). AlmaLinux ELevate, wiki.almalinux.org/elevate (the CentOS migration staircase). CentOS end-of-life dates from the CentOS project.

22.3 The Debian family: stepwise dist-upgrade

Debian's method is different in shape: there is no single rewrite tool, there is a documented, disciplined walk, and the release notes for the target version are the procedure, not optional background reading. You point apt at the new release's codename, refresh, do a minimal upgrade to move the running system gently, then a full upgrade that is allowed to remove packages to complete the transition. Debian also moves one release at a time (12 to 13, not 12 to 14 in one go).

# Debian: bookworm (12) -> trixie (13), on a snapshot, after reading the release notes
# # edit /etc/apt/sources.list and /etc/apt/sources.list.d/*: bookworm -> trixie
# apt update
# apt upgrade --without-new-pkgs  # the gentle first step
# apt full-upgrade  # allow removals to finish the move
# reboot

Ubuntu wraps the same idea in do-release-upgrade, which by default moves between LTS releases (skipping the interim ones) and which insists you disable third-party PPAs before it will proceed, an opinion Debian leaves to you and your judgement.

Two different risk shapes

leapp rewrites the system in a dedicated boot environment, so the dangerous work happens outside the running OS; Debian's apt full-upgrade transforms the live, running system in place. Neither is safer in the abstract, but they fail differently: a leapp run aborts and leaves you to restore, while an interrupted apt full-upgrade can leave a half-converted system that needs dpkg --configure -a and a steady hand. Both reasons point to the same rule in 22.5.

22.4 The hazards both families share

Whatever the tool, the same handful of things cause almost every failed upgrade, and they are worth checking before you start rather than discovering at the reboot. Third-party repositories and PPAs are the single most common cause: a package from a repo that has no build for the new release blocks the transaction or, worse, half-upgrades. Removed or obsolete packages leave a system carrying software the new release no longer ships. The mandatory-access-control relabel (a full SELinux relabel on the Red Hat family, AppArmor profile changes on Debian) can surprise a service whose access pattern shifts. A full /boot stops a new kernel from installing. And bootloader and default changes across the major (GRUB configuration, a service whose previously valid config is now rejected) turn up at first boot. Inventory these on the specific host before the upgrade; the leapp report and the Debian release notes both call most of them out if you read them.

22.5 Backing out: the snapshot is the only real undo

This is the rule the whole chapter exists to deliver. Neither method has a true rollback. leapp does not un-upgrade a system, and Debian's apt cannot walk a release backward; in both worlds "undo" means "restore the snapshot you took first." So the discipline is non-negotiable: never begin a major upgrade on a host you cannot snapshot and restore, and make the production run your second run by rehearsing the whole thing on a clone. Backups and tested restores are Chapter 17; assessing the box before you touch it is Chapter 21.

Caution

The two ways a major upgrade goes badly wrong are starting it without a tested snapshot, and starting it with an un-audited third-party repo still enabled. Resolve every leapp inhibitor, read the Debian release notes end to end, and disable or account for every non-distribution repository before you begin. An upgrade you cannot undo, on a system you do not fully understand, is how a routine maintenance window becomes an outage.

Best practice

Clone the host (or restore its backup onto a scratch VM) and perform the entire upgrade there first. The clone tells you which inhibitors you will hit, how long the run takes, and whether the service still works on the far side, so the production upgrade is a rehearsed procedure rather than an experiment on something that matters.

Lab 20 · Rehearse both upgrades, read both reports

Goal: produce a leapp preupgrade report on the Red Hat side and a simulated dist-upgrade on the Debian side, on snapshots, and read what each one is warning you about before changing anything.

# Red Hat family: generate the inhibitor report and read it
# dnf install -y leapp-upgrade
# leapp preupgrade
# less /var/log/leapp/leapp-report.txt  # work through every "inhibitor"

# Debian: simulate the full-upgrade and read the removals
# # on a snapshot, point sources at trixie, then:
# apt update
# apt -s full-upgrade  # -s simulates; note what it wants to REMOVE

On the Red Hat box, every inhibitor in the report is a thing you must fix before leapp upgrade will run; on the Debian box, the simulated removals are your early warning about obsolete or third-party packages. For the inherited CentOS 7 Grimoire Box, the first real step is the ELevate move to AlmaLinux 8; follow the current ELevate guide rather than these representative commands, because the repository URLs and data packages change between releases.

Exercise

You inherit a CentOS 7 host and need it on AlmaLinux 10. Why can you not get there in one upgrade, how many discrete major steps does it take, and what is the single thing you must do before the first step that would let you recover if step two fails?

Capstone

Everything at once, on one bench. The capstone assembles every layer the book taught into a single hardened, documented, recoverable host, built on two families in parallel so the differences are visible end to end and labeled by the chapter that explains them.

Chapter 23Build, Harden, and Document the Grimoire Box on Two Families

This is where every part of the book becomes one system.

We build the Grimoire Box from a blank VM to a hardened, audited, recoverable host on Debian 13 and AlmaLinux 10 in parallel, with each step labeled by the chapter that taught it, then verify the whole thing against a table and close the loop by inheriting and recovering the box we just built. If you can do this capstone on both families, you can administer a Linux server.

23.1 The build, step by step, each tagged to its chapter

The build is the book in order. Each step is the same idea on both families, diverging only where the earlier chapters said it would:

# 1. Install from a stock ISO, minimal      (Ch 3)
# 2. Data volume: LVM + filesystem at /srv/git, hardened mount   (Ch 6)
# 3. Accounts: git service user, alice admin, sudo via the right group   (Ch 5)
# 4. SSH: keys only, root login off, verified with sshd -T   (Ch 9)
# 5. Service: hardened systemd unit (or rootless Quadlet container; dnf install git-daemon on RHEL)   (Ch 7, Ch 19)
# 6. Firewall: default-deny, allow SSH + git only   (Ch 10)
# 7. Time + limits: chrony/timesyncd, CPU/Memory caps on the service   (Ch 11)
# 8. Logging: persistent journal, confirm auditing   (Ch 7, Ch 18)
# 9. MAC: confirm SELinux enforcing / AppArmor active   (Ch 15)
# 10. Baseline: apply CIS/STIG via SCAP, generate the crosswalk   (Ch 13, Ch 16)
# 11. Backup: nightly restic + a tested restore   (Ch 17)
# 12. Automate: capture the whole build as an Ansible playbook   (Ch 20)

The only steps that differ in substance between Debian and AlmaLinux are the ones flagged all along: the package and firewall front ends, the sudo group, the MAC system, and the SSH service name. Everything else is identical, which is the entire thesis of the book demonstrated in one build.

23.2 The verification table

A build you cannot verify is a hope. Each layer has a command that proves it and an expected result; run them on both families and the host is not "probably fine," it is demonstrably correct.

LayerChapterVerifyExpected
Data volume mounted, hardened6findmnt /srv/gitmounted, nodev,nosuid
SSH keys-only9sshd -T | grep passwordauthpasswordauthentication no
Service confined7systemd-analyze security grimoire-gitlow exposure score
Service actually serving7git ls-remote git://localhost/<repo>.gitrefs returned (not "repository not exported")
Firewall default-deny10nft list rulesetonly SSH + git allowed
Resource caps11systemctl show grimoire-git -p MemoryMaxthe cap you set
MAC enforcing15getenforce / aa-statusenforcing / profiles loaded
Baseline passes13oscap xccdf eval --profile cis...target pass rate met
Restore works17restic restore + diffrestored data matches

23.3 Closing the loop: inherit what you built

The final move ties the greenfield build to the operational reality the book opened with. Take the host you just built, imagine it two years on, neglected and a major version behind, and run the inheritance drill from Chapter 21 against it: assess it read-only, snapshot it, and either upgrade it across the major with the right tool for its family (Chapter 22) or rebuild and migrate the data onto a fresh host. Doing this to your own clean build, where you know exactly what is on it, is the safest possible place to practice the most dangerous routine task in administration, and it leaves you ready to do it to a box you did not build.

Best practice

The real deliverable of this capstone is not the running host; it is the Ansible playbook that rebuilds it. When the build exists as code, the host becomes disposable in the best sense: you can destroy it and recreate it, stand up an identical second one, or recover from a lost machine in minutes. A hand-built host is a liability you maintain; a coded one is an asset you reproduce. That shift is what separates someone who can install Linux from someone who can run it.

Exercise

Build the Grimoire Box end to end on both Debian 13 and AlmaLinux 10, then run the verification table on each. List every step whose substance (not just syntax) differed between the families, and confirm it matches the set this book flagged from Chapter 1 onward: packaging, firewall front end, sudo group, MAC system, and SSH service name. If you found a divergence not on that list, you have found either a bug in your build or an omission in the book; both are worth chasing down.

Appendices

The reference layer: the place the trivial cross-family differences live so the chapters do not have to carry them, plus the master standards crosswalk and the supporting tables a field reference needs.

Appendix A · Cross-Family Command & Path Reference

This is the one place the "phrasebook" content belongs: the same task, the literal command on each family, with no reasoning, because the reasoning is in the chapters. Use it at the keyboard; read the chapters to understand it. This is a representative extract; the full appendix expands each row.

TaskDebian / UbuntuRHEL / AlmaLinux / FedoraArch
Install a packageapt install NAMEdnf install NAMEpacman -S NAME
Get the git daemon commandapt install git (bundled)dnf install git-daemon (separate subpackage)pacman -S git (bundled)
Refresh package indexapt updatednf check-updatepacman -Sy (only with -u)
Apply all updatesapt full-upgradednf upgradepacman -Syu
Search for a packageapt search NAMEdnf search NAMEpacman -Ss NAME
Enable + start a servicesystemctl enable --now NAME  (identical: this is the systemd layer)
Firewall front endufw (over nftables)firewall-cmd (over nftables)nft directly
Network config front endifupdown (Debian) / Netplan (Ubuntu)NetworkManagersystemd-networkd
Default /bin/shdashbashbash
Mandatory access controlAppArmorSELinuxneither by default
Become-root groupsudowheelwheel
In-place major upgradeapt full-upgrade per releaseleapprolling (no major upgrade)
Hardening baseline availableCIS; STIG on Ubuntu onlyDISA STIG + CISnone (Distribution-Independent only)
SSH service unit namesshsshdsshd
Default time syncsystemd-timesyncdchrony(you choose)
Default host firewallnone active (ufw inactive)firewalld activenone
Persistent text logjournald only (Debian); /var/log/syslog (Ubuntu)/var/log/messagesjournald only
View a service's logsjournalctl -u NAME  (identical: the systemd journal)
Authentication toolingedit common-* PAM stacksauthselectedit PAM directly

Appendix B · Standards Crosswalk Master Table

The master crosswalk maps every control the book builds to the authorities it answers to, across both families, as a standalone audit reference. It is governed by the discipline of Chapter 16: the NIST SP 800-53 control families are stable and named directly, while the per-family STIG and CIS identifiers are derived from the current SCAP Security Guide content, not transcribed, because they renumber between revisions. Only identifiers verifiable as of this writing are shown concretely; the rest are marked for generation from the SSG, which is the actual state of a crosswalk and the reason it is regenerated rather than memorized.

Control areaNIST 800-53RHEL / AlmaLinux (STIG / CIS)Debian / Ubuntu (STIG / CIS)Built in
Mandatory access control enforcingAC-3, AC-6STIG RHEL-09-431010 (CAT I, RHEL 9), RHEL-10-700420 (CAT II, RHEL 10); CIS MACUbuntu STIG / CIS AppArmor (verify)15
Root SSH login disabledAC-6, IA-2STIG / CIS SSH (verify in SSG)STIG / CIS SSH (verify in SSG)9
Key-based SSH, passwords offIA-2, IA-5verify in SSGverify in SSG9
Host firewall, default-denySC-7firewalld / nftables (verify)ufw / nftables (verify)10
Password length and lockoutIA-5, AC-7STIG 15-char min (verify)CIS pwquality (verify)5, 14
Partition mount optionsCM-7, SC-39CIS 1.1 (verify)CIS 1.1 (verify)6
Kernel sysctl hardeningSC-7, SI-16verify in SSGverify in SSG14
Audit logging (auditd)AU-2, AU-12STIG / CIS audit (verify)STIG / CIS audit (verify)13, 18
Automatic security updatesSI-2dnf-automatic (verify)unattended-upgrades (verify)4
Time synchronizationAU-8chrony (verify)timesyncd / chrony (verify)11

"Verify in SSG" means: generate the exact STIG finding and CIS section from the current SCAP Security Guide profile for that distribution (Chapter 13), rather than trusting a transcribed number. The NIST control identifiers are from SP 800-53 Rev 5 and are stable; the SELinux-enforcing STIG identifier is shown as a worked example and should still be reconfirmed against the current STIG.

Appendix C · Glossary

The working vocabulary of the book, in one place. Where a term has a family-specific counterpart (the firewall front end, the become-root group, the MAC system), the entry names both and points at the chapter that teaches the difference.

Anaconda
The Red Hat family's installer, graphical and hub-and-spoke. Every interactive install writes its answers as a replayable Kickstart file at /root/anaconda-ks.cfg (Chapter 3).
AppArmor
The mandatory access control system on Debian and Ubuntu. Confines a program by path: a profile lists the files and capabilities an executable may use, in enforce or complain mode. Simpler and more legible than SELinux, less comprehensive. Contrast with SELinux.
AUR (Arch User Repository)
A community collection of user-submitted build recipes (PKGBUILD files) for Arch. Unvetted by design: read every PKGBUILD before building, prefer the official repositories, and never run an AUR helper as root.
Bastion (jump host)
A controlled host you connect through to reach systems that are not directly exposed. OpenSSH reaches past it natively with ProxyJump (ssh -J), so the internal host's exposure is not weakened to administer it.
Boolean (SELinux)
A named on/off switch that tunes SELinux policy without editing it (getsebool, setsebool), the supported way to adapt the targeted policy to a service.
Btrfs
A copy-on-write filesystem with snapshots, checksumming, and subvolumes built in. Default on Fedora Workstation (since Fedora 33) and openSUSE; offered by AlmaLinux 10 at install; not shipped by RHEL. Its built-in RAID 5/6 is still considered unstable.
cgroups v2 (control groups)
The unified kernel hierarchy that limits and accounts for a process group's CPU, memory, and I/O. The default on every current family; systemd exposes it through unit directives such as CPUQuota, MemoryMax, and TasksMax (Chapter 11).
chrony
A full NTP implementation, the default time service on the Red Hat family and the right choice on any server needing accurate, disciplined time, or that serves time to others. Contrast with systemd-timesyncd.
cloud-init
The tool that configures a fresh cloud instance, or an Ubuntu Subiquity install, on first boot from supplied metadata. The shared machinery behind Ubuntu's cloud presence.
Containerfile
The build recipe (a Dockerfile by another name) defining an OCI container image layer by layer, built with podman build or docker build.
Crypto policy (system-wide)
On the Red Hat family, a single setting (update-crypto-policies --set DEFAULT|FUTURE|FIPS) that fixes the approved ciphers, MACs, and key-exchange algorithms for the whole system at once, SSH and TLS included. It can override what sshd_config appears to say (Chapter 9).
DAC (discretionary access control)
The ordinary Linux permission model: the owner of a thing decides who may use it, and root may do anything. The layer that MAC sits above. Contrast with MAC.
dash
The small, strictly-POSIX shell that is /bin/sh on the Debian family (bash is /bin/sh on the Red Hat family and Arch). A #!/bin/sh script using a bashism works on AlmaLinux and silently fails on Debian (Chapter 2).
Distribution
Someone's opinionated assembly of a kernel, a userland, a package manager, default configuration, a release cadence, and a support promise. There is no neutral "Linux"; every install is a distribution.
dnf
The high-level package manager on the Red Hat family (successor to yum), operating on .rpm packages over the low-level rpm.
ELevate
The AlmaLinux project that extends leapp with cross-distribution data so a CentOS host can migrate onto AlmaLinux, one major version at a time (Chapter 22).
Enforcing / permissive (SELinux)
The two active SELinux modes: enforcing blocks and logs policy violations; permissive only logs them. A permissive or disabled system is a Category I finding under the RHEL 9 STIG (RHEL-09-431010); the RHEL 10 STIG keeps the requirement but rates it Category II (RHEL-10-700420).
ext4
The conservative, mature default filesystem on Debian and Ubuntu; resizes with resize2fs, growing online (mounted) and shrinking offline (unmounted). Among the three default choices only XFS cannot shrink; Btrfs resizes both ways too. Contrast with XFS and Btrfs.
FHS (Filesystem Hierarchy Standard)
The standard (current version 3.0, 2015) defining what each top-level directory is for. The conceptual map; man hier on the running system is the live authority, since systems have moved on (the /usr merge, the move of /var/run to /run).
firewalld
The host-firewall front end on the Red Hat family, organizing rules into zones over nftables and driven by firewall-cmd. Active by default on a fresh install. Compare ufw.
fstab
/etc/fstab, the table of persistent mounts keyed by UUID. Several of its mount options (nodev, nosuid, noexec) are security controls the benchmarks require on specific partitions (Chapter 6).
GPT (GUID Partition Table)
The modern partitioning scheme that replaced legacy MBR, removing the four-primary-partition limit and the 2 TB ceiling.
Idempotence
The property that running an automation task once or many times leaves the same result, because it describes desired state ("git is installed") rather than steps that break if repeated. The core discipline of configuration management (Chapter 20).
initramfs
A small temporary root filesystem the bootloader loads alongside the kernel, holding just enough to find and mount the real root.
Journal (systemd journal)
The structured log systemd-journald captures from every service, read with journalctl. On systemd 257 the lab distros diverge: AlmaLinux 10 is volatile (no /var/log/journal), Debian 13 is persistent (it ships the directory, as Fedora does); systemd v259 changed the upstream default to persistent (Chapter 7).
Kickstart
The replayable answer file an Anaconda install writes to /root/anaconda-ks.cfg, and the Red Hat family's unattended-install mechanism. Compare preseed (Debian) and cloud-init autoinstall (Ubuntu).
leapp
Red Hat's supported in-place major-version upgrade tool: a preupgrade report, then an upgrade performed in a dedicated boot environment. Moves one major at a time (8 to 9, 9 to 10); a hand-rolled distro-sync is not supported.
Lingering
The loginctl enable-linger setting that starts a user's systemd instance at boot and keeps it running with no active session, so a rootless user service (a Podman container) survives logout and starts at boot.
LVM (Logical Volume Manager)
The indirection layer between partitions and filesystems: physical volumes pool into a volume group from which logical volumes are carved, so storage can grow online, span disks, snapshot, and migrate (Chapter 6).
MAC (mandatory access control)
A system-wide, kernel-enforced policy confining even a root-running process to what the policy allows, regardless of file ownership. SELinux on the Red Hat family, AppArmor on Debian and Ubuntu. Contrast with DAC.
NetworkManager
The network configuration front end on the Red Hat family (driven by nmcli, storing keyfiles; the older ifcfg network-scripts are deprecated). Compare Netplan, systemd-networkd, and ifupdown.
nftables
The kernel firewall engine that replaced iptables. firewalld and ufw are front ends that generate nftables rules; nft list ruleset shows the rules they produced.
nodev, nosuid, noexec
Mount options that are security controls: nodev ignores device files, nosuid ignores setuid bits, noexec forbids executing binaries from the filesystem. The benchmarks require combinations of them on data partitions to shrink where an attacker can stage and run code.
OpenSCAP
The scanner (oscap) that evaluates a system against a SCAP profile and can generate remediation, the same content underlying vendor compliance tooling (Chapter 13).
PAM (Pluggable Authentication Modules)
The framework a login consults instead of checking a password itself, running stacks of modules across four phases (auth, account, password, session). Stacks live in /etc/pam.d/; a careless edit can lock everyone out (Chapter 5).
pacman
Arch's package manager, operating on a rolling repository (pacman -Syu) plus the AUR.
Podman
A daemonless, rootless container engine whose command line mirrors Docker's. Run rootless, a container's "root" maps through user namespaces to an unprivileged host UID, so a breakout lands in one unprivileged account rather than at root (Chapter 19).
POSIX
The portable contract (POSIX.1-2024 / IEEE Std 1003.1-2024 / The Open Group Base Specifications Issue 8) defining the shell language, the standard utilities, and the C system-interface API. The line this book uses to separate portable behavior from a distribution's extensions.
PPA (Personal Package Archive)
An Ubuntu mechanism letting anyone publish a repository you add with one command. Convenient and unvetted; treat add-apt-repository ppa:... like curl | sudo bash.
preseed
Debian's unattended-install answer mechanism. Compare Kickstart (Red Hat) and cloud-init autoinstall (Ubuntu).
Quadlet
The Podman feature (merged into Podman 4.4) that turns a declarative .container file into a systemd-generated service, replacing the deprecated podman generate systemd.
restic
A backup tool giving deduplicated, encrypted, incremental copies of data directories; the default for the Grimoire Box. BorgBackup is an equivalent.
Rootless container
A container run under an ordinary user account, supervised by that user's systemd instance via user namespaces. A breakout lands as an unprivileged user, not root; defense in depth when combined with systemd sandboxing.
SCAP / SCAP Security Guide
The Security Content Automation Protocol, and the open-source SCAP Security Guide (the ComplianceAsCode project) that ships machine-readable hardening profiles (STIG, CIS Levels 1 and 2, PCI-DSS, the German BSI baseline, and others) together with their remediation.
SELinux
The mandatory access control system on the Red Hat family, labeling every process and file with a type and enforcing type-enforcement rules. The default targeted policy confines network-facing services; adapt it with booleans and labels, not by disabling it. Its own Grimoire volume goes deeper. Contrast with AppArmor.
setuid
The bit that makes a binary run with its owner's privileges rather than the caller's, the controlled mechanism behind passwd and sudo. The danger is a planted setuid-root binary on a writable filesystem, which nosuid neutralizes.
Snapshot (LVM)
A near-instant, point-in-time copy of a logical volume, useful for a consistent backup or a pre-upgrade safety net. Copy-on-write and fixed-size, so it must be sized and watched; a snapshot on the same disk is not a backup.
STIG (Security Technical Implementation Guide)
A U.S. Department of Defense configuration standard at assigned severities (Category I/II/III). DISA publishes STIGs for RHEL 9 and 10 and for Canonical Ubuntu, but not for Debian or Arch (Chapter 13).
sudo / wheel
sudo grants and logs a controlled escalation to root. Membership in a group confers it: the sudo group on Debian and Ubuntu, the wheel group on the Red Hat family and Arch. The names are convention, not something built in (Chapter 5).
systemd
The init system and service manager (PID 1) on every mainstream family. Manages units, resolves dependencies, captures logs to the journal, and confines services with sandboxing directives. Near-universal but not universal (Alpine and Devuan opt out).
Target (systemd)
A named synchronization point that groups units and marks a boot milestone, the modern replacement for runlevels (for example multi-user.target).
Timer (systemd)
A .timer unit that triggers a .service on a schedule, the modern alternative to cron. Logs to the journal, can depend on other units, and with Persistent=true catches up a run missed while the machine was off.
ufw (uncomplicated firewall)
The host-firewall front end on Debian and Ubuntu, over nftables. Installed but inactive by default on Ubuntu, absent on a fresh Debian. Allow SSH before enabling it, or you cut your own session.
Unit (systemd)
The declarative file describing one thing systemd manages: .service, .socket, .target, .timer, .mount, .slice. A unit in /etc/systemd/system overrides the vendor copy; a drop-in fragment overrides a single directive.
Userland
Everything around the kernel: the C library, the core utilities, the shell, and the programs a working system needs. Mostly shared across distributions, which is why skills transfer at all.
XFS
The default filesystem on the Red Hat family, built for scale and heavy parallel I/O. Grows online (xfs_growfs) but never shrinks. Contrast with ext4.
3-2-1 rule
The backup discipline: at least three copies, on two kinds of media, with one off the host entirely. A snapshot, or any copy on the same machine, does not count as the off-host copy (Chapter 17).

Appendix D · References

Every source below is primary or authoritative: the standards bodies, the distribution and project documentation, and the upstream tooling. For versioned standards the identifier and release are given; for living documents the URL points to the current version, so confirm the version before relying on a specific value. This is the source of truth behind every Standard callout in the book.

IdentifierDocumentURL / Location
POSIX-2024POSIX.1-2024 / IEEE Std 1003.1-2024 / The Open Group Base Specifications Issue 8 (June 2024). Freely readable online.https://pubs.opengroup.org/onlinepubs/9799919799/
MAN-PAGESThe Linux man-pages project (release 6.18), the authority for actual Linux behavior on the running system.https://www.kernel.org/doc/man-pages/
FHS-3Filesystem Hierarchy Standard 3.0 (2015), the Linux Foundation.https://refspecs.linuxfoundation.org/fhs.shtml
NIST-800-53NIST SP 800-53 Rev 5, Security and Privacy Controls for Information Systems and Organizations (the control catalog: AC, IA, SC, AU, SI, CM families).https://doi.org/10.6028/NIST.SP.800-53r5
NIST-800-123NIST SP 800-123, Guide to General Server Security.https://doi.org/10.6028/NIST.SP.800-123
NIST-800-190NIST SP 800-190, Application Container Security Guide.https://doi.org/10.6028/NIST.SP.800-190
DISA-STIGDISA Security Technical Implementation Guides: Red Hat Enterprise Linux 9 (v2r8, April 2026), Red Hat Enterprise Linux 10 (v1r1, June 2026), Canonical Ubuntu 24.04 LTS (v1r5, May 2026). DoD Cyber Exchange.https://public.cyber.mil/stigs/
CIS-BENCHCIS Benchmarks: Red Hat Enterprise Linux 10 v1.0.1, Debian Linux 13 v1.0.0, Ubuntu Linux 24.04 LTS, and Distribution-Independent Linux v2.0.0. Center for Internet Security.https://www.cisecurity.org/cis-benchmarks
DOD-SRGDoD Cloud Computing Security Requirements Guide (SRG), cited for the DoD acceptance of CIS Benchmarks where no STIG exists. Confirm the current wording before relying on it in an audit artifact.https://public.cyber.mil/dccs/
SCAP-SSGSCAP Security Guide / ComplianceAsCode content (STIG, CIS, PCI-DSS, BSI, and other profiles, with Ansible and Bash remediation).https://github.com/ComplianceAsCode/content
OPENSCAPOpenSCAP scanner and the oscap tool.https://www.open-scap.org/
KERNELThe Linux Kernel Archives (current and longterm release status; 7.0 stable, 6.18 longterm).https://www.kernel.org/
DEBIANDebian 13 (trixie) Release Notes, the Debian Policy Manual, and the Debian Social Contract.https://www.debian.org/releases/trixie/
UBUNTUUbuntu release cycle and Ubuntu Server documentation.https://ubuntu.com/about/release-cycle
RHEL-DOCSRed Hat Enterprise Linux documentation, including Using SELinux, Configuring and managing networking, and the Upgrading guides (8 to 9, 9 to 10).https://docs.redhat.com/
ALMAAlmaLinux Wiki and Release Notes (10.2 "Lavender Lion", May 2026; ELevate migration).https://wiki.almalinux.org/
ELEVATEAlmaLinux ELevate, the CentOS and EL major-version migration project and data.https://almalinux.org/elevate/
FEDORAFedora documentation and release schedule (Fedora 44, April 2026).https://docs.fedoraproject.org/
ARCHThe Arch Wiki and the Arch Installation Guide.https://wiki.archlinux.org/
CENTOS-EOLCentOS Linux end-of-life notice (CentOS 7: 30 June 2024; CentOS 8: 31 December 2021).https://www.redhat.com/en/topics/linux/centos-linux-eol
SYSTEMDsystemd manual: systemd.exec(5), systemd.service(5), journald.conf(5), systemd-analyze(1) (current series v260).https://www.freedesktop.org/software/systemd/man/latest/
PODMANPodman and Quadlet documentation: podman-systemd.unit(5), rootless and daemonless containers.https://docs.podman.io/
GITEAGitea, a self-hosted Git service distributed as a maintained container image (the off-the-shelf option for the container lab).https://docs.gitea.com/
BTRFSBtrfs documentation, including the feature Status page (RAID 5/6 stability).https://btrfs.readthedocs.io/
LVM2LVM2 documentation and man pages (pvcreate, vgcreate, lvcreate, lvextend).https://sourceware.org/lvm2/
OPENSSHOpenSSH manual pages: sshd_config(5), ssh_config(5), ssh(1).https://www.openssh.com/manual.html
FIREWALLnftables wiki, firewalld documentation, and the ufw manual (the host-firewall engine and its front ends).https://wiki.nftables.org/
CHRONYchrony documentation (the NTP implementation and chronyc).https://chrony-project.org/
RESTICrestic backup documentation (deduplicated, encrypted, incremental backups). BorgBackup is the equivalent alternative.https://restic.readthedocs.io/
ANSIBLEAnsible documentation (inventory, playbooks, modules, roles, idempotence).https://docs.ansible.com/
SELINUX-VOLCompanion volume: Enforcing, Confining & Hardening with SELinux, The Programmer's Grimoire. The deep treatment of SELinux policy.See the SELinux edition (selinux/index.html) in this series.

Errata and Updates

This guide is corrected continuously, and you are part of how that happens. If you find an error, a claim that no longer matches its primary source, a command that does not behave as printed, or anything that has simply gone stale, report it to [email protected]. Name the section, and where you can, the authority that settles it; that is exactly how the book is verified in the first place, and a good report can go straight into the next revision.

The current, corrected version always lives at https://gregvogt.net/grimoire/. Each edition was correct as of the revision date printed on its cover, and claims nothing beyond it: standards move, packages update, and the page in front of you ages from the day it ships. When a detail matters, check it against the latest revision there, and against the primary source it cites, before you rely on it.

How to Cite This Guide

Because this is a living document, cite the revision you used and where you found it, so that a reader can retrieve the same text you saw. The revision is printed on the cover.

Vogt, Greg. Operating, Hardening & Recovering Linux. The Programmer’s Grimoire. Revision v1.1-RC1 · June 2026. https://gregvogt.net/grimoire/linux/

For LaTeX and reference managers:

@misc{grimoire-linux,
  author  = {Vogt, Greg},
  title   = {Operating, Hardening \& Recovering Linux},
  series  = {The Programmer's Grimoire},
  edition = {Revision v1.1-RC1 · June 2026},
  year    = {2026},
  url     = {https://gregvogt.net/grimoire/linux/}
}

License and Reuse

The Programmer’s Grimoire is published free of charge and licensed to you under a Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0). You are free to read, copy, share, and adapt or translate it, in any medium or format, for any non-commercial purpose, on one condition: give appropriate credit to the author, link to the license, and indicate whether you changed anything. You may not use the material for commercial purposes. The full terms are at https://creativecommons.org/licenses/by-nc/4.0/.

The intent is plain. The knowledge is meant to be free for anyone to read, copy, and translate, and the non-commercial term is what keeps it that way, so that no one else fences it off or resells it. A paid edition, where one exists, comes from the author and exists only to support the work; the knowledge itself is not the thing being sold.

Trademark and brand. The name The Programmer’s Grimoire, the series wordmark, and the look and branding of these guides are trademarks of Greg Vogt and are not part of the content license above. Reusing the licensed text, including in a translation, grants no right to the Grimoire name or brand. You may not present your version as an official Grimoire, use the name or wordmark to label, endorse, or promote a derivative or third-party work, or otherwise imply that the author stands behind it. Credit the original by name, which is the attribution the license requires, but publish your version under your own title.

Colophon

Each guide is a single HTML document with an external stylesheet and a small progressive-enhancement script, and no inline style or script at all, so it satisfies a strict Content-Security-Policy. Three formats are built from that one source: the PDF with WeasyPrint, the EPUB with EbookLib (parsed with BeautifulSoup), and the Kindle AZW3 with Calibre’s ebook-convert. What you read on screen, on paper, and on an e-reader is the same text rendered three ways.

The reading text is set in Georgia, with the bundled Literata as the press fallback; display headings, numerals, and labels are set in Cinzel, code and the interface in JetBrains Mono (with a bundled fallback face for full glyph coverage), and the Grimoire wordmark in UnifrakturCook. On screen the reader can switch the prose to Atkinson Hyperlegible or OpenDyslexic, scale the type, adjust line spacing, and toggle dark mode; the print and e-reader builds stay in the typeset faces. The bundled fonts are under the SIL Open Font License.

How it was made is described in the notes at the front, and is the point as much as the prose. First drafts are generated by an AI (Claude, made by Anthropic) and then verified, line by line, against primary sources by a human before anything ships. Every factual claim is tracked in a per-volume claims ledger and re-checked against the living standards on each revision, which is why a guide carries a revision date, and why that date is load-bearing.