update_windows_acl.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """``hermes update``'s owed ``windows_home_acl`` step: after an elevated update, give the same
  2. user back access to the home tree that run may have left Administrators-only (#139870, #134889 W8).
  3. Split from ``update_cmd_maint.py``."""
  4. import logging
  5. logger = logging.getLogger("hermes_cli.update_cmd")
  6. def repair_windows_home_acl(*, elevated: bool | None = None) -> None:
  7. """Restore access for the filtered UAC token after an elevated update.
  8. An elevated process can create home-tree entries whose DACL only grants
  9. Administrators and SYSTEM. Administrators is deny-only in the normal UAC
  10. token, so grant the actual user SID explicitly on every entry under the home.
  11. The walk never descends into or grants through a junction, symlink or hard link
  12. (``hermes_dir_acl.grant_tree_user_access``): ``icacls /T`` follows junctions, so a
  13. same-user junction inside the home would have turned the elevated grant into full
  14. control of e.g. ``C:\\Program Files\\X``.
  15. *elevated* is the host fact (default: probed; False on every host but an elevated Windows one).
  16. """
  17. from hermes_dir_acl import grant_tree_user_access, process_is_elevated
  18. if not (process_is_elevated() if elevated is None else elevated):
  19. # Only an elevated update leaves Administrators-only entries, and only an elevated token
  20. # can rewrite them; a recursive grant over the whole home on every update costs minutes.
  21. return
  22. from hermes_constants import get_hermes_home
  23. home = get_hermes_home()
  24. # The home itself is the operator's choice and may be a link: pin its real directory and walk
  25. # below it (links beneath are still never followed).
  26. granted, skipped, failed = grant_tree_user_access(home, pin_root=True, elevated=True)
  27. if failed and not granted:
  28. path, reason = failed[0]
  29. raise RuntimeError(f"could not restore user access to {home}: {path}: {reason}")
  30. if not granted:
  31. # Nothing took (the root itself was skipped or unreadable): the step stays owed, never a
  32. # silent success that leaves stranded state stranded.
  33. why = f"{skipped[0]} is a junction, symlink or hard link" if skipped else "nothing was walkable"
  34. raise RuntimeError(f"could not restore user access to {home}: nothing was repaired ({why})")
  35. if failed:
  36. # Like icacls /C: keep going, report the first few; the step stays owed only when nothing took.
  37. logger.warning("Restoring user access under %s failed for %d entr%s, e.g. %s: %s", home, len(failed),
  38. "y" if len(failed) == 1 else "ies", failed[0][0], failed[0][1])