16.4. Repairing Accounts, Packages, and Full Filesystems

Once the system boots and the root is writable, the remaining failures are inside the running system: an administrative account that cannot authenticate, a package operation that was interrupted, a filesystem that has no free space or no free inodes, or a deleted file that a process still holds open. These problems do not require separate media if the system is reachable, but they do require a trusted shell and a clear record of what was changed. The chroot from Section 16.2 is the trusted environment when the normal login is not available.

16.4.1. Recovering Administrative Access from a Trusted Environment

If the only administrative account is locked or its password is unknown, the repair is a password reset from a shell that already has root. On a running system, use sudo from another administrative account; if none is available, use the rescue/emergency shell or the installer's chroot. The chroot on the recovery copy stands in for the installed root. Create a test account there for the exercise:

$ sudo chroot /mnt/recovery /usr/sbin/useradd -m -s /bin/bash recoverytest

The command is silent on success. It creates the home directory and the standard skeleton files using the chroot's /etc/skel and /etc/default/useradd. Lock the account to model a disabled login:

$ sudo chroot /mnt/recovery /usr/bin/passwd -l recoverytest
passwd: password changed.

passwd -l writes a ! in front of the stored hash, which prevents password authentication without deleting the password. The message says "password changed" because the shadow entry changed, not because a new password was set. Check the status:

$ sudo chroot /mnt/recovery /usr/bin/passwd -S recoverytest
recoverytest L 2026-11-21 0 99999 7 -1

The second field is L for locked, P for a usable password, or NP for no password. The remaining fields are the last-change date, minimum age, maximum age, warning period, and inactivity period; -1 means no inactivity limit. Now set a new password. The command prompts twice and does not echo the password:

$ sudo chroot /mnt/recovery /usr/bin/passwd recoverytest
New password: Retype new password: passwd: password updated successfully

The prompts do not echo the password; the captured line simply shows them in sequence. The account is now usable:

$ sudo chroot /mnt/recovery /usr/bin/passwd -S recoverytest
recoverytest P 2026-11-21 0 99999 7 -1

The P confirms that the hash is present and the account is not locked. The change is written to the mounted root's /etc/shadow, not the rescue environment's. If the account was locked with usermod -L rather than passwd -l, unlock it with usermod -U; both commands edit the same shadow field, but passwd -S reports the result. An expired account shows P with a last-change date in the past and an expiration field that has passed; use chage -l recoverytest to see the policy and chage -d today recoverytest to reset the last-change date when that is the actual problem.

A password reset does not repair a broken sudo policy. Check the sudoers syntax with visudo -c from the chroot, which parses the main file and every drop-in without opening an editor:

$ sudo chroot /mnt/recovery /usr/sbin/visudo -c
/etc/sudoers: parsed OK
/etc/sudoers.d/10-ch16-john: parsed OK
/etc/sudoers.d/README: parsed OK
/etc/sudoers.d/vagrant: parsed OK

The exact list depends on the system's drop-ins; the /etc/sudoers.d/vagrant entry belongs to the box image, and 10-ch16-john is this book's lab rule for john's sudo access - on a normal installation john's access comes from the sudo group and neither drop-in is present. A syntax error is reported with the file and line number. Repair it with visudo on the mounted file (visudo -f /mnt/recovery/etc/sudoers) or edit the offending drop-in and re-run the check. Do not delete /etc/sudoers to "start over"; a missing file can lock every administrator out. If the root account itself is locked, passwd root from the trusted shell is the direct repair; if the root filesystem is mounted read-only, remount it read-write first, as described in Section 16.2.2.

Test the new credentials inside the chroot rather than assuming the password file is enough:

$ sudo chroot /mnt/recovery /bin/su - recoverytest -c id
uid=1002(recoverytest) gid=1002(recoverytest) groups=1002(recoverytest)

su performs the PAM password check and starts a login shell for the account; id proves which identity the shell received. The command prompts for the password, which is not echoed. If it fails with "Authentication failure", the password or the account state is still wrong; if it fails with a PAM configuration error, the chroot's /etc/pam.d or the bind-mounted /dev is incomplete. The test account's UID and GID are local to the copy and need not match the installed system's numbering.

On a machine whose boot loader works but whose root password is unknown, the console procedure is to add init=/bin/bash at the GRUB editor. init=/bin/bash starts a shell instead of systemd; the root filesystem may be mounted read-only, so remount it with mount -o remount,rw /, reset the password, and then reboot with exec /sbin/init or the machine's reset button. Debian's initramfs-tools also accepts break=mount on the kernel command line to stop in the (initramfs) shell before the root filesystem is mounted; that shell is useful for inspecting the mount stage, but the password reset needs the root mounted and writable, so init=/bin/bash is the direct path. This console procedure bypasses PAM and most services. It is a console-only operation: the GRUB editor and the shell are on the machine's display. It is not a remote repair, and it leaves no audit trail unless you record the commands. The chroot method above is preferable when rescue media is available because it leaves the running system's state untouched.

The chroot repairs are complete. Leave the chroot first with exit if you are still inside an interactive shell, then unmount the bind mounts from the rescue environment, deepest mount first:

$ sudo umount /mnt/recovery/dev/pts
$ sudo umount /mnt/recovery/dev
$ sudo umount /mnt/recovery/sys
$ sudo umount /mnt/recovery/proc

Each command is silent on success. Unmounting /dev before /dev/pts fails because the nested mount is still active; the order matters. The mounted root and ESP stay in place for the remaining checks and can be unmounted at the end of the exercise. If umount reports "target is busy", use findmnt -R /mnt/recovery, lsof +D /mnt/recovery, or fuser -vm /mnt/recovery to find the process; do not use umount -l as the first response, because a lazy unmount can hide a still-running repair process.

16.4.2. Repairing Interrupted Package Operations Offline

An interrupted apt or dpkg run leaves the package database with a package that is unpacked but not configured, or with a lock file that a dead process still owns. The first symptom is usually an apt error saying that dpkg was interrupted and that dpkg --configure -a must be run. Do not delete the lock file while a package manager is actually running; check for a live process first. On a normal system, fuser /var/lib/dpkg/lock-frontend names the process holding the lock, and ps confirms whether it is alive. If the process is gone, the lock is stale; if it is alive, wait for it or stop it cleanly. The lock files are /var/lib/dpkg/lock, /var/lib/dpkg/lock-frontend, and the apt lists lock, not one file.

The exercise reproduces an interrupted installation by downloading a small package and unpacking it without configuring it. Download it into the workspace:

$ apt-get download cowsay
Get:1 https://deb.debian.org/debian trixie/main amd64 cowsay all 3.03+dfsg2-8 [21.4 kB]
Fetched 21.4 kB in 0s (58.1 kB/s)

The file is written into the current directory, which is the reader workspace; apt-get download does not install anything and does not need root. Unpack it as root without configuring:

$ sudo dpkg --unpack /home/john/debian-handbook/recovery/cowsay_*.deb
Selecting previously unselected package cowsay.
(Reading database ... 28420 files and directories currently installed.)
Preparing to unpack .../cowsay_3.03+dfsg2-8_all.deb ...
Unpacking cowsay (3.03+dfsg2-8) ...
Processing triggers for man-db (2.13.1-1) ...

The package's files are now on disk, but its postinst has not run. dpkg --audit reports the state:

$ sudo dpkg --audit
The following packages have been unpacked but not yet configured.
They must be configured using dpkg --configure or the configure
menu option in dselect for them to work:
 cowsay               configurable talking cow

dpkg --audit exits 0 even when it finds problems; the report is the output, not the exit status. The package is in the unpacked state, not installed. Configure everything that is pending:

$ sudo dpkg --configure -a
Setting up cowsay (3.03+dfsg2-8) ...

The -a option configures all unpacked packages, not only this one. It runs the package's postinst and any pending triggers. A failure here is a real package problem: read the error, fix the cause (missing directory, failing service start, or a script bug), and run dpkg --configure -a again. Do not purge the package while it is half-configured unless you intend to remove it; apt purge may refuse to proceed until the database is consistent, and dpkg --purge --force-all can leave dependencies broken.

Confirm the package is installed:

$ sudo dpkg -s cowsay | grep ^Status
Status: install ok installed

A second audit should be silent:

$ sudo dpkg --audit

No output means there are no packages in the unpacked, half-configured, or half-installed states that dpkg --audit reports. apt-get check and apt --fix-broken install are the dependency-level checks: apt-get check reads the package lists and builds the dependency tree without changing anything, while apt --fix-broken install proposes the changes needed to satisfy missing dependencies. On a system with a half-configured package, dpkg --configure -a is usually the smaller and more direct repair; use apt --fix-broken install when dependencies, not the package's own script, are the problem. Both commands can download packages, so a rescue environment needs working network access or a local package cache.

The same sequence works inside the chroot. Package scripts run with the chroot's /proc and /dev available, and they see the mounted root's package database and files. The package cache can be copied into the chroot if the network is unavailable; dpkg --configure -a uses the already-unpacked files and does not need the archive. If the package database itself is corrupt, restore /var/lib/dpkg/status and /var/lib/dpkg/status-old from a backup or from the rescue copy, then run dpkg --audit before any further installation. Chapter 6 covers the database layout, apt's sources, and the supported repair commands.

16.4.3. Reclaiming Space and Inodes Without Losing Diagnostic Evidence

A full filesystem stops services in ways that look unrelated: a database cannot write its journal, a package cannot unpack, a log cannot rotate, and a login session may fail when it cannot create a temporary file. Check both counters before deleting anything. df -h reports block use and df -i reports inode use; a filesystem can have plenty of free blocks and no free inodes, especially when it holds many small files. The practice exercise uses a small loop-backed ext4 image so the failure is quick and does not consume the data volume. Create the image in the workspace:

$ truncate -s 128M full.img

The command creates a sparse file of the requested size; it is silent. Create an ext4 filesystem on it and mount it:

$ sudo mkfs.ext4 -q -F -L fulldemo /home/john/debian-handbook/recovery/full.img
$ sudo mkdir -p /mnt/fulldemo
$ sudo mount -o loop /home/john/debian-handbook/recovery/full.img /mnt/fulldemo

The mkfs command is quiet with -q; the mount is silent. -F forces mkfs.ext4 to operate on a regular file rather than refusing because the target is not a block device. -L sets the label. The loop device is allocated by the kernel; findmnt /mnt/fulldemo shows the /dev/loopN source. Fill the filesystem with a file until the write fails:

$ sudo dd if=/dev/zero of=/mnt/fulldemo/fill.bin bs=1M
dd: error writing '/mnt/fulldemo/fill.bin': No space left on device
112+0 records in
111+0 records out
117280768 bytes (117 MB, 112 MiB) copied, 2.9102 s, 40.3 MB/s

dd exits nonzero because the last write failed; the bytes copied are still on disk. The error is the expected result of the exercise, not a command failure to hide. The filesystem now has no free blocks for ordinary users:

$ df -h /mnt/fulldemo
Filesystem      Size  Used Avail Use% Mounted on
/dev/loop0      115M  112M     0 100% /mnt/fulldemo

The size is smaller than the 128 MiB image because ext4 reserves space for metadata and root; the Use% is 100% and Avail is 0. Identify the file that filled it before deleting anything:

$ sudo du -h /mnt/fulldemo/fill.bin
112M    /mnt/fulldemo/fill.bin

du reports allocated blocks per file; du -xhd1 /mnt/fulldemo gives a one-level summary that stays on the filesystem. Preserve any log or diagnostic file before removing it, then remove the practice file:

$ sudo rm /mnt/fulldemo/fill.bin

Space is released immediately because no process holds the file open:

$ df -h /mnt/fulldemo
Filesystem      Size  Used Avail Use% Mounted on
/dev/loop0      115M   46K  106M   1% /mnt/fulldemo

If df does not show the space after rm, a process is still holding the file open; Section 16.4.4 covers that case. The same du/rm sequence works on a real data volume. Before deleting, copy the largest files and the relevant logs to the backup media; a full filesystem is often the first symptom of a runaway log or a deleted-but-open file, and the file names are the evidence that identifies the cause.

Inode exhaustion has the same shape but a different counter. Create a second image with a deliberately small inode count:

$ truncate -s 128M inodes.img
$ sudo mkfs.ext4 -q -F -N 1024 -L inodedemo /home/john/debian-handbook/recovery/inodes.img

-N 1024 sets the number of inodes; a normal mkfs.ext4 on this size would create many more. Mount it and create empty files until the inode table is exhausted:

$ sudo mkdir -p /mnt/inodes
$ sudo mount -o loop /home/john/debian-handbook/recovery/inodes.img /mnt/inodes
$ sudo -i
# for i in $(seq 1 1100); do : > /mnt/inodes/file-$i || break; done
bash: /mnt/inodes/file-1013: No space left on device
# exit

The loop stops at the first failed creation. The || break handles the failed redirection and ends the loop; the shell's error remains visible because the exercise does not hide it. The exact stopping point depends on the filesystem's reserved inodes and lost+found. Check the inode table:

$ df -i /mnt/inodes
Filesystem     Inodes IUsed IFree IUse% Mounted on
/dev/loop1       1024  1024     0  100% /mnt/inodes

IUsed equals Inodes and IFree is zero, even though the filesystem may still have free blocks. Count the files that were created:

$ sudo find /mnt/inodes -maxdepth 1 -type f | wc -l
1012

The count is lower than the inode total because the filesystem reserves some inodes and lost+found consumes one. Remove the files and verify the inode count returns:

$ sudo rm -f /mnt/inodes/file-*
$ df -i /mnt/inodes
Filesystem     Inodes IUsed IFree IUse% Mounted on
/dev/loop1       1024    12  1012    2% /mnt/inodes

The 12 remaining inodes include lost+found and the filesystem's own metadata. On a real system, find the directory consuming inodes with find /mountpoint -xdev -type f | wc -l, and find large files with du -xhd1. A mail queue, a session directory, or a cache with millions of tiny files is a common cause; deleting the cache is safe only after checking what owns it. journalctl --vacuum-size=500M and apt-get clean reclaim space from system logs and package archives, but they do not reclaim inodes unless their files are removed; read Chapter 8 and Chapter 6 before running either on a production system.

Unmount the practice images when the exercise is complete:

$ sudo umount /mnt/fulldemo
$ sudo umount /mnt/inodes

Both commands are silent. The image files stay in the workspace after the unmount; they are sparse, so keeping them for a repeat run costs little, and rm full.img inodes.img deletes them once you are finished. Do not leave loop mounts behind across a reboot: the loop devices are recreated, but the mount points and the underlying files remain.

16.4.4. Handling Deleted but Open Files

On Unix, deleting a file removes its directory entry and decrements its link count, but the blocks are not freed until every open file descriptor is closed. A log file that was rotated by rm instead of by a copy-and-truncate sequence can therefore consume gigabytes after df appears to show it gone. lsof lists open files, and its +L1 selector shows files whose link count is less than one - in practice, deleted files that are still open. In the workspace, as john, create a log and start a holder for it:

$ mkdir -p logs
$ printf "application started\n" > logs/application.log
$ sudo systemd-run --unit=logholder --property=User=john --property=WorkingDirectory=/home/john /usr/bin/tail -f /home/john/debian-handbook/recovery/logs/application.log
Running as unit: logholder.service; invocation ID: 4f6c053de5de48029d969be9878d919f

The unit is transient: it exists until it is stopped or the machine reboots, and it runs as john so the file ownership is realistic. In a normal service you would use the service's own unit and restart it; the transient unit is only a way to keep the demonstration's process visible while several commands run.

Remove the file while the holder keeps its descriptor open:

$ sudo rm /home/john/debian-handbook/recovery/logs/application.log

The command is silent. Now list the deleted-but-open file:

$ sudo lsof +L1 | grep application.log
tail    18929 john 3r   REG  254,1       20     0 393238 /home/john/debian-handbook/recovery/logs/application.log (deleted)

The columns are the command, process ID, user, file descriptor, type, device, size, inode, and path; (deleted) is the marker that matters. The file size is 20 bytes and the inode is 393238. The process is a tail -f started for the exercise; it holds file descriptor 3. The same information is visible through /proc:

$ sudo ls -l /proc/$(systemctl show -p MainPID --value logholder)/fd
total 0
lr-x------ 1 john john 64 Nov 21 03:24 0 -> /dev/null
lrwx------ 1 john john 64 Nov 21 03:24 1 -> socket:[42750]
lrwx------ 1 john john 64 Nov 21 03:24 2 -> socket:[42750]
lr-x------ 1 john john 64 Nov 21 03:24 3 -> /home/john/debian-handbook/recovery/logs/application.log (deleted)
lr-x------ 1 john john 64 Nov 21 03:24 4 -> anon_inode:inotify

The 3 -> ... (deleted) line identifies the open descriptor. The process ID is read from systemd because the lab keeps the holder alive as a transient unit; on an ordinary system use the PID from lsof or pgrep tail. For a log file, truncating the open descriptor releases the blocks without killing the process:

$ sudo truncate -s 0 /proc/$(systemctl show -p MainPID --value logholder)/fd/3

The command is silent. The file is still open and still marked deleted, but its size is zero:

$ sudo lsof +L1 | grep application.log
tail    18929 john 3r   REG  254,1        0     0 393238 /home/john/debian-handbook/recovery/logs/application.log (deleted)

The blocks are now free; the process continues writing at the new end of file. This is the safe operation for a log whose contents are not needed. It is not safe for an application data file: truncating a database or a mailbox through /proc corrupts it. For a data file, stop the application, let it close the descriptor, and restore the file from backup or recreate it; do not truncate a live data file just to reclaim space.

The alternative is to restart the service that holds the file. Identify the unit with systemctl status or systemctl list-units | grep, then systemctl restart UNIT; the old process closes the descriptor and the new one opens the file by path. If the service cannot be restarted immediately, truncate buys time for a log, but the correct long-term fix is to change the rotation rule to copytruncate or to signal the process to reopen its log (Chapter 8). Stop the lab holder when finished:

$ sudo systemctl stop logholder.service

The command is silent. The container of the unit disappears and the deleted inode is released. Use lsof +L1 again to confirm; on a busy system, filter by the mount point or the user to keep the list readable. The +L1 selector is specific to lsof; find /proc/*/fd -lname '* (deleted)' is a shell-only fallback, but it requires care with permissions and filenames containing spaces.