Skip to content

Bugfixes omd py - #249

Open
lgmu wants to merge 27 commits into
labsfrom
bugfixes-omd-py
Open

lgmu wants to merge 27 commits into
labsfrom
bugfixes-omd-py

Conversation

@lgmu

@lgmu lgmu commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Several OMD CLI operations could hang, report success after failure, or modify files outside the intended site directory. This PR fixes these issues in omd.py.

Filesystem and restore fixes:

  • Prevent root temporary-directory cleanup from following symlinks to external data, including during directory replacement races.
  • Anchor recursive ownership changes to open directory descriptors while retaining the existing scandir() traversal.
  • Validate backup destinations before extraction or unlinking. Reject path traversal, unexpected site prefixes, and external hard-link targets while preserving legitimate OMD symlinks.
  • Use the requested version when creating a site's version symlink.
  • Abort copy/move operations when rsync fails, preventing mv --reuse from removing the source after an incomplete copy. Pass exclusion patterns as literal subprocess arguments.

Process and command handling fixes:

  • Prevent parallel commands from hanging when child output lacks a final newline.
  • Drain stdout and stderr before checking password-setting and diagnostic subprocess results, avoiding pipe deadlocks.
  • Parse PID files as integers, reject nonpositive PIDs, and distinguish missing processes from permission errors.
  • Return failure from whole-site restarts when either stopping or starting services fails.
  • Correct success reporting for failed commands and signal termination, and fix the inverted exit-status check when mounting multiple sites.
  • Pass disable --kill to the correct unmount parameter and preserve unmount failure reporting.

Configuration, update, and output fixes:

  • Report configuration-setting hook failures and preserve hook-adjusted values in interactive configuration.
  • Stop dry-run merges from retrying unreadable skeleton files indefinitely, clean up temporary files, and use bytes for the empty-skeleton fallback.
  • Report permission-only differences and forward the requested diff program through both file and directory traversal.
  • Explicitly restore stdout/stderr and close log files when logging stops, including cleanup when one close operation fails.

Validation used focused local reproductions covering symlink replacement races, malicious archive paths, subprocess output exceeding pipe capacity, trailing output without newlines, failure exit statuses, configuration-hook results, diff behavior, and logging lifecycle. Restore regression checks passed on Python 3.9 and 3.14. The branch diff passes git diff --check.

lgmu added 18 commits November 11, 2026 16:31
Detect stdout EOF separately from temporarily unavailable data and flush any remaining output before collecting the child exit status. This prevents the parallel output loop from waiting forever when a subprocess exits without a final newline.
Pass the kill flag by name to unmount_tmpfs instead of assigning it to the output parameter. This enables process killing when requested and preserves error reporting so unmount failures abort before disabling the Apache configuration.
Stop the merge attempt after recording an unreadable skeleton conflict during a dry run, and clean up temporary files before returning. This avoids retrying the same failed read indefinitely or attempting a patch with incomplete inputs.

Use bytes for the empty-skeleton fallback to match the binary template replacement code.
Use boolean success values consistently in show_success and convert Apache command results explicitly. This prevents exit code 1 and failed unmounts from being displayed as successful, including commands terminated by signals.

Treat nonzero child exit codes as failures when mounting all sites instead of marking successful mounts as failures.
Return the combined stop and start status instead of implicitly returning None. Restart now exits with a failure status if either phase fails, while preserving the existing service order and execution of both phases.

Correct the indentation of the service result return statements.
Abort configuration changes when the setting hook fails instead of silently returning success. Let config_set_value own value selection and persistence so interactive configuration preserves hook-adjusted values and avoids duplicate saves and hook runs.
List, inspect, open, and chown entries relative to held directory descriptors instead of resolving their paths again. Refuse symlinks when opening child directories and avoid following links during ownership changes.

Use os.listdir with a directory descriptor to retain Python 3.6 compatibility.
Keep the existing scandir traversal while opening child directories relative to the held parent descriptor and changing ownership without following symlinks. Directory or symlink replacements can no longer redirect ownership changes through entry paths.
Reject archive members outside the expected site prefix, absolute or parent-traversal paths, destinations escaping through symlinks, and external hard-link targets before extraction or unlinking existing files.

Preserve external symlink targets used by valid OMD backups, including the version link.
Honor the version argument instead of always linking to the executing OMD version. This keeps restored sites linked to the version selected for their restored configuration.
Parse PID-file contents as integers before probing processes and reject nonpositive PIDs to avoid process-group checks. Distinguish missing processes from permission denial so live processes are not treated as stale.

Handle malformed or oversized PID values without masking unrelated programming errors, retaining the process-matching fallback.
Run rsync with checked subprocess arguments and report nonzero exits or launch failures before changing ownership, patching files, or finalizing the destination. In particular, a failed mv --reuse copy no longer proceeds to remove the source site.

Pass exclusion patterns as literal arguments instead of interpolating them into a shell command.
Drain stdout and stderr with communicate before inspecting the subprocess return code. This prevents password setting from blocking on unread stdout and diagnostic scripts from blocking while the parent waits for exit.

Preserve password-setting stderr responses and diagnostic output classification.
Include permission changes when deciding whether a skeleton entry differs, so permission-only changes are displayed and counted in the diff exit status.

Forward the selected diff program through both single-file and directory traversal paths instead of discarding it.
Replace destructor-based stream restoration with an explicit close method called by stop_logging. This releases both log files even while wrappers still have references, and prevents later cleanup from overwriting replacement streams.

Clear logging globals and attempt stderr cleanup even when closing the stdout log fails.
Pass the unresolved site tmp path to root cleanup so resolving a symlink cannot bypass the existing refusal check. Open the site and tmp directories without following symlinks, then traverse and delete relative to held directory descriptors.

Preserve non-root cleanup behavior and support for the installation symlink.
@lgmu
lgmu requested review from lausser and sni November 12, 2026 14:15
Ahmet Oeztuerk added 9 commits November 13, 2026 15:22
Tar archives can contain character devices, block devices, FIFOs and
other special members.  The path validation added earlier only checks
member names; it does not inspect the member type.  tar.extract(),
including with filter='tar', still creates device nodes as root, and
chown_tree() then gives them to the site user.

A crafted backup could therefore place a block device such as major 8,
minor 0 (/dev/sda) inside the restored site.  After restore the site user
would own a node for the raw device (subject to device cgroup, nodev or
SELinux restrictions), which is a serious privilege escalation risk on a
normal host installation.

Allow only regular files, directories, symlinks and hard links in
extract_backup_file().  Reject all other member types before any
filesystem operation.  This also covers character devices and FIFOs.

Normal backup/restore still works.  Verified with a regular OMD backup
and restore, and with crafted BLKTYPE, CHRTYPE and FIFOTYPE members,
which are now rejected without creating a node.
omd restore validates archive members while extracting them, after
shutil.rmtree() has already removed an existing site.  A corrupted or
crafted backup therefore destroys the current site even if restore
fails on a later member.

Validate every archive member before changing the site, including path
containment, member types, hard-link targets and complete archive
readability.  Extract into a hidden sibling staging directory.  For a
reuse restore, move the old site aside and rename the completed staging
tree into place; restore the old tree on extraction failure.  Keep the
old tree until finalization succeeds, then remove it.  New-site restores
use the same staging path.

Reopen the archive for the extraction pass after preflight and reject
truncated archives cleanly.  Non-root users who cannot write to
/omd/sites still use the preflighted in-place path; root restores are
fully staged.

Tested normal reuse, new-site and non-root restores, crafted traversal,
device and FIFO archives, and truncated archives.  The existing site
remained intact on failures, and no staging or old directories were left
after successful restores.  The file compiles under Python 3.6, 3.8 and
3.12.
A backup can contain an internal symlink whose target is outside the
site.  The archive path passes path validation, but patch_template_file
later opens the .skel.<site> sibling with plain open(), which follows the
symlink and lets a crafted backup write arbitrary files as root.

Reject symlink targets outside the restored site, the archive site's own
root (needed for absolute links in existing backups) and the root-owned
OMD version tree.  Normal version and version-tree links keep working.

Harden patch_template_file as well: create .skel temporary files with
O_NOFOLLOW and refuse to patch through symlinked dst/.orig/.rej paths.
This protects both restore and cp/mv even if a symlink is created after
archive validation or validation is missed.

Tested normal restore to a new site, a reuse restore and a non-root
restore; normal omd cp; an external /tmp symlink attack rejected; an
internal .skel symlink attack rejected without modifying the target;
normal version and absolute site/version-tree links still restored.
The file compiles under Python 3.6, 3.8 and 3.12.
chown_tree_fd opened each directory relative to its parent descriptor but
still enumerated it with os.scandir(dirpath).  That performed a fresh path
lookup, so a site user could rename a directory and substitute another
directory or symlink during a root chown traversal.  The chown calls were
fd-relative and did not follow symlinks, so this did not chown files
outside the site, but entries could be skipped or chowned under the wrong
names.

Use os.listdir(dir_fd) and lstat each single-component name with
os.stat(..., dir_fd=..., follow_symlinks=False).  Recurse by name and
parent fd, and chown non-directories with dir_fd and
follow_symlinks=False.  This removes the path lookup from the traversal
and works on Python 3.6.

Tested with a temporary tree containing regular files, nested
directories, and symlinks to a root-owned victim directory.  All site
entries were chowned, the symlinks themselves were chowned, and the
victim target was untouched.  Also tested normal omd create, cp and
restore operations and the Python 3.6, 3.8 and 3.12 builds.
The permission-only diff handling compared get_skel_permissions() with
get_file_permissions(), but the latter follows symlinks.  Symlink modes
are ignored by Linux, so this reported every symlink whose target had a
different mode as a permission change.  It also produced entries like
0000 -> 0600 for dangling versus non-dangling links.  Skip permission
comparison whenever either side is a symlink.

Python's tar filter also clears group/other write bits while extracting.
OMD backups contain site files and directories with group-write
permissions (for example 0770 and 0660), so a restore on Python 3.12
changed those permissions to 0750 and 0640 and then showed them as diff
changes.  Restore the archived mode after extraction for regular files
and directories; symlink and hard-link modes are left alone.
Removing a stale pid file is routine cleanup, but writing the warning to
stderr makes normal commands fail tests that expect quiet operation, for
example omd rm after a service was killed while testing a core dump.

Keep the diagnostic available with -v, but do not emit it by default.
Add regression coverage for the restore hardening commits:

- reject character-device and FIFO members before extraction
- reject symlinks whose target escapes the site
- reject a malicious .backup_meta/skel symlink
- reject path traversal in archive member names
- verify an existing site is left intact when preflight rejects an archive

The crafted archives are generated from a normal backup by a small helper in
t/data/omd, avoiding version-specific binary fixtures.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant