Spaces:
Running

noqt commited on
Commit
e579122
·
1 Parent(s): a6e7438

fix: resume interrupted uninstallation

Browse files
scripts/uninstall.py CHANGED
@@ -25,6 +25,7 @@ import json
25
  import os
26
  import pwd
27
  import shutil
 
28
  import subprocess
29
  import time
30
  from pathlib import Path
@@ -43,6 +44,9 @@ TMPFILES = Path("/etc/tmpfiles.d/lumi-eggcracker.conf")
43
  STATE = Path("/var/lib/lumi-eggcracker")
44
  RUNTIME = Path("/run/lumi-eggcracker")
45
  WATCHDOG_RUNTIME = Path("/run/lumi-eggcracker-watchdog")
 
 
 
46
  PREFIX = "lumi-eggcracker-workload-"
47
  SUPERVISOR = "lumi-eggcracker.service"
48
  WATCHDOG = "lumi-eggcracker-watchdog.service"
@@ -51,6 +55,27 @@ SERVICE_CGROUPS = (
51
  SYSTEM_SLICE / SUPERVISOR,
52
  SYSTEM_SLICE / WATCHDOG,
53
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
 
56
  def digest(path: Path) -> str:
@@ -61,6 +86,207 @@ def digest(path: Path) -> str:
61
  return value.hexdigest()
62
 
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def run(argv: list[str]) -> subprocess.CompletedProcess[str]:
65
  return subprocess.run(argv, capture_output=True, text=True, check=False, timeout=60)
66
 
@@ -166,18 +392,18 @@ def empty_stopped_service_cgroup(path: Path) -> None:
166
 
167
 
168
  def uninstall() -> int:
 
 
169
  manifest_path = STATE / "install-manifest.json"
170
  if manifest_path.is_symlink() or not manifest_path.is_file():
171
  raise SystemExit("installed manifest is missing")
172
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
173
- if manifest.get("schema_version") != "lumi-eggcracker.install.v5":
174
- raise SystemExit("installed manifest schema is invalid")
175
- for name, expected in manifest.get("files", {}).items():
176
- path = Path(name)
177
- if path.is_symlink() or not path.is_file() or digest(path) != expected:
178
- raise SystemExit(f"refusing uninstall because installed file drifted: {path}")
179
  if not owned_cgroups_empty() or not quarantine_empty():
180
  raise SystemExit("refusing uninstall with populated or uncertain Eggcracker cgroups")
 
181
  supervisor_stopped = False
182
  watchdog_stopped = False
183
  try:
@@ -193,29 +419,17 @@ def uninstall() -> int:
193
  raise SystemExit("refusing uninstall because cgroups remained populated after stop")
194
  reset_failed(SUPERVISOR)
195
  reset_failed(WATCHDOG)
196
- for path in (UNIT, WATCHDOG_UNIT, TMPFILES, BIN, LIB, ETC, STATE, RUNTIME, WATCHDOG_RUNTIME):
197
  if path.exists() and not path.is_symlink():
198
  shutil.rmtree(path) if path.is_dir() else path.unlink()
199
- if manifest.get("created_workload_user"):
200
- try:
201
- account = pwd.getpwnam(str(manifest["workload_user"]))
202
- except KeyError:
203
- account = None
204
- if account and account.pw_uid == manifest.get("workload_uid"):
205
- require_success(["/usr/sbin/userdel", account.pw_name])
206
- if manifest.get("created_workload_group"):
207
- try:
208
- group = grp.getgrnam(str(manifest.get("workload_group", "")))
209
- except KeyError:
210
- group = None
211
- if group:
212
- require_success(["/usr/sbin/groupdel", group.gr_name])
213
  require_success(["/usr/bin/systemctl", "daemon-reload"])
214
  # Removing the unit files can leave transient ``not-found`` objects in
215
  # the manager. A global reset after the daemon reload lets systemd
216
  # garbage-collect them. Naming a removed unit here would recreate the
217
  # very not-found object the uninstall verifier rejects.
218
  require_success(["/usr/bin/systemctl", "reset-failed"])
 
219
  except BaseException:
220
  # A refused or interrupted transaction must not leave protection
221
  # disabled. Best-effort restoration is deliberately attempted for
 
25
  import os
26
  import pwd
27
  import shutil
28
+ import stat
29
  import subprocess
30
  import time
31
  from pathlib import Path
 
44
  STATE = Path("/var/lib/lumi-eggcracker")
45
  RUNTIME = Path("/run/lumi-eggcracker")
46
  WATCHDOG_RUNTIME = Path("/run/lumi-eggcracker-watchdog")
47
+ UNINSTALL_JOURNAL = Path("/var/lib/lumi-eggcracker-uninstall-journal.json")
48
+ UNINSTALL_JOURNAL_SCHEMA = "lumi-eggcracker.uninstall-transaction.v1"
49
+ MAX_UNINSTALL_JOURNAL_BYTES = 64 * 1024
50
  PREFIX = "lumi-eggcracker-workload-"
51
  SUPERVISOR = "lumi-eggcracker.service"
52
  WATCHDOG = "lumi-eggcracker-watchdog.service"
 
55
  SYSTEM_SLICE / SUPERVISOR,
56
  SYSTEM_SLICE / WATCHDOG,
57
  )
58
+ TARGETS = (
59
+ UNIT,
60
+ WATCHDOG_UNIT,
61
+ TMPFILES,
62
+ BIN,
63
+ LIB,
64
+ ETC,
65
+ STATE,
66
+ RUNTIME,
67
+ WATCHDOG_RUNTIME,
68
+ )
69
+ DIRECTORY_TARGETS = {LIB, ETC, STATE, RUNTIME, WATCHDOG_RUNTIME}
70
+ MANIFEST_FILES = {
71
+ BIN,
72
+ ETC / "detector_catalogue.json",
73
+ ETC / "policy.json",
74
+ LIB / "lumi-eggcracker.pyz",
75
+ TMPFILES,
76
+ UNIT,
77
+ WATCHDOG_UNIT,
78
+ }
79
 
80
 
81
  def digest(path: Path) -> str:
 
86
  return value.hexdigest()
87
 
88
 
89
+ def write_uninstall_journal(manifest: dict[str, object]) -> int:
90
+ account = pwd.getpwnam(str(manifest["workload_user"]))
91
+ workload_gid = account.pw_gid
92
+ value = {
93
+ "manifest": manifest,
94
+ "schema_version": UNINSTALL_JOURNAL_SCHEMA,
95
+ "uninstaller_sha256": digest(Path(__file__)),
96
+ "workload_gid": workload_gid,
97
+ }
98
+ payload = (json.dumps(value, sort_keys=True) + "\n").encode()
99
+ if len(payload) > MAX_UNINSTALL_JOURNAL_BYTES:
100
+ raise SystemExit("uninstall transaction journal is too large")
101
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW
102
+ descriptor = os.open(UNINSTALL_JOURNAL, flags, 0o600)
103
+ try:
104
+ pending = memoryview(payload)
105
+ while pending:
106
+ written = os.write(descriptor, pending)
107
+ if written < 1:
108
+ raise OSError("uninstall transaction write made no progress")
109
+ pending = pending[written:]
110
+ os.fsync(descriptor)
111
+ except BaseException:
112
+ os.close(descriptor)
113
+ descriptor = -1
114
+ if UNINSTALL_JOURNAL.exists() and not UNINSTALL_JOURNAL.is_symlink():
115
+ UNINSTALL_JOURNAL.unlink()
116
+ raise
117
+ finally:
118
+ if descriptor >= 0:
119
+ os.close(descriptor)
120
+ installer.fsync_directory(UNINSTALL_JOURNAL.parent)
121
+ return workload_gid
122
+
123
+
124
+ def remove_uninstall_journal() -> None:
125
+ UNINSTALL_JOURNAL.unlink(missing_ok=True)
126
+ installer.fsync_directory(UNINSTALL_JOURNAL.parent)
127
+
128
+
129
+ def validate_manifest_structure(manifest: object) -> dict[str, object]:
130
+ if not isinstance(manifest, dict):
131
+ raise SystemExit("installed manifest is invalid")
132
+ if manifest.get("schema_version") != "lumi-eggcracker.install.v5":
133
+ raise SystemExit("installed manifest schema is invalid")
134
+ files = manifest.get("files")
135
+ targets = manifest.get("targets")
136
+ if (
137
+ not isinstance(files, dict)
138
+ or any(not isinstance(name, str) for name in files)
139
+ or {Path(name) for name in files} != MANIFEST_FILES
140
+ or any(
141
+ not isinstance(value, str)
142
+ or len(value) != 64
143
+ or any(character not in "0123456789abcdef" for character in value)
144
+ for value in files.values()
145
+ )
146
+ or not isinstance(targets, list)
147
+ or len(targets) != len(TARGETS)
148
+ or {Path(value) for value in targets if isinstance(value, str)} != set(TARGETS)
149
+ ):
150
+ raise SystemExit("installed manifest inventory is invalid")
151
+ if (
152
+ not isinstance(manifest.get("operator"), str)
153
+ or not isinstance(manifest.get("operator_uid"), int)
154
+ or not isinstance(manifest.get("workload_user"), str)
155
+ or not isinstance(manifest.get("workload_group"), str)
156
+ or not isinstance(manifest.get("workload_uid"), int)
157
+ or not isinstance(manifest.get("created_workload_user"), bool)
158
+ or not isinstance(manifest.get("created_workload_group"), bool)
159
+ ):
160
+ raise SystemExit("installed manifest identity is invalid")
161
+ return manifest
162
+
163
+
164
+ def read_uninstall_journal() -> tuple[dict[str, object], int]:
165
+ try:
166
+ metadata = UNINSTALL_JOURNAL.lstat()
167
+ except FileNotFoundError as error:
168
+ raise SystemExit("uninstall transaction journal disappeared") from error
169
+ if (
170
+ not stat.S_ISREG(metadata.st_mode)
171
+ or metadata.st_uid != 0
172
+ or metadata.st_gid != 0
173
+ or stat.S_IMODE(metadata.st_mode) != 0o600
174
+ or not 1 <= metadata.st_size <= MAX_UNINSTALL_JOURNAL_BYTES
175
+ ):
176
+ raise SystemExit("uninstall transaction journal has unsafe metadata")
177
+ try:
178
+ value = json.loads(UNINSTALL_JOURNAL.read_text(encoding="utf-8"))
179
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
180
+ raise SystemExit("uninstall transaction journal is invalid") from error
181
+ if (
182
+ not isinstance(value, dict)
183
+ or set(value)
184
+ != {"manifest", "schema_version", "uninstaller_sha256", "workload_gid"}
185
+ or value.get("schema_version") != UNINSTALL_JOURNAL_SCHEMA
186
+ or value.get("uninstaller_sha256") != digest(Path(__file__))
187
+ or not isinstance(value.get("workload_gid"), int)
188
+ ):
189
+ raise SystemExit("uninstall transaction journal identity is invalid")
190
+ return validate_manifest_structure(value.get("manifest")), value["workload_gid"]
191
+
192
+
193
+ def validate_remaining_targets(manifest: dict[str, object], allow_missing: bool) -> None:
194
+ files = manifest["files"]
195
+ if not isinstance(files, dict):
196
+ raise SystemExit("installed manifest inventory is invalid")
197
+ for name, expected in files.items():
198
+ path = Path(name)
199
+ if not path.exists() and not path.is_symlink():
200
+ if allow_missing:
201
+ continue
202
+ raise SystemExit(f"refusing uninstall because installed file drifted: {path}")
203
+ if path.is_symlink() or not path.is_file() or digest(path) != expected:
204
+ raise SystemExit(f"refusing uninstall because installed file drifted: {path}")
205
+ operator = pwd.getpwnam(str(manifest["operator"]))
206
+ if operator.pw_uid != manifest["operator_uid"] or operator.pw_uid == 0:
207
+ raise SystemExit("installed operator identity changed")
208
+ for path in TARGETS:
209
+ try:
210
+ metadata = path.lstat()
211
+ except FileNotFoundError:
212
+ continue
213
+ expected_type = stat.S_IFDIR if path in DIRECTORY_TARGETS else stat.S_IFREG
214
+ allowed_gids = {0, operator.pw_gid} if path == RUNTIME else {0}
215
+ if (
216
+ stat.S_IFMT(metadata.st_mode) != expected_type
217
+ or path.is_symlink()
218
+ or metadata.st_uid != 0
219
+ or metadata.st_gid not in allowed_gids
220
+ or (stat.S_ISREG(metadata.st_mode) and metadata.st_nlink != 1)
221
+ ):
222
+ raise SystemExit(f"refusing unsafe uninstall target: {path}")
223
+
224
+
225
+ def systemctl_allow_absent(action: str, unit: str) -> None:
226
+ result = run(["/usr/bin/systemctl", action, unit])
227
+ detail = (result.stderr + result.stdout).lower()
228
+ absent = any(
229
+ marker in detail
230
+ for marker in ("not loaded", "not found", "does not exist", "no such file")
231
+ )
232
+ if result.returncode and not absent:
233
+ raise SystemExit(result.stderr.strip() or result.stdout.strip() or "systemctl failed")
234
+
235
+
236
+ def remove_manifest_identity(manifest: dict[str, object], workload_gid: int) -> None:
237
+ if manifest["created_workload_user"]:
238
+ try:
239
+ account = pwd.getpwnam(str(manifest["workload_user"]))
240
+ except KeyError:
241
+ account = None
242
+ if account is not None:
243
+ supplementary = set(os.getgrouplist(account.pw_name, account.pw_gid))
244
+ if (
245
+ account.pw_uid != manifest["workload_uid"]
246
+ or account.pw_uid == 0
247
+ or account.pw_shell not in {"/usr/sbin/nologin", "/sbin/nologin"}
248
+ or account.pw_dir != "/nonexistent"
249
+ or supplementary != {account.pw_gid}
250
+ ):
251
+ raise SystemExit("refusing to remove changed workload identity")
252
+ require_success(["/usr/sbin/userdel", account.pw_name])
253
+ if manifest["created_workload_group"]:
254
+ try:
255
+ group = grp.getgrnam(str(manifest["workload_group"]))
256
+ except KeyError:
257
+ group = None
258
+ if group is not None:
259
+ if group.gr_gid != workload_gid or group.gr_mem:
260
+ raise SystemExit("refusing to remove changed workload group")
261
+ if any(account.pw_gid == group.gr_gid for account in pwd.getpwall()):
262
+ raise SystemExit("refusing to remove a workload group still in use")
263
+ require_success(["/usr/sbin/groupdel", group.gr_name])
264
+
265
+
266
+ def recover_uninstall() -> int:
267
+ manifest, workload_gid = read_uninstall_journal()
268
+ validate_remaining_targets(manifest, allow_missing=True)
269
+ systemctl_allow_absent("stop", SUPERVISOR)
270
+ systemctl_allow_absent("disable", SUPERVISOR)
271
+ systemctl_allow_absent("stop", WATCHDOG)
272
+ systemctl_allow_absent("disable", WATCHDOG)
273
+ for service_cgroup in SERVICE_CGROUPS:
274
+ empty_stopped_service_cgroup(service_cgroup)
275
+ if not owned_cgroups_empty() or not quarantine_empty():
276
+ raise SystemExit("refusing recovery because Eggcracker cgroups remain populated")
277
+ for path in TARGETS:
278
+ if path.exists() and not path.is_symlink():
279
+ shutil.rmtree(path) if path.is_dir() else path.unlink()
280
+ remove_manifest_identity(manifest, workload_gid)
281
+ require_success(["/usr/bin/systemctl", "daemon-reload"])
282
+ require_success(["/usr/bin/systemctl", "reset-failed"])
283
+ if any(path.exists() or path.is_symlink() for path in TARGETS):
284
+ raise SystemExit("uninstall recovery left an Eggcracker target")
285
+ remove_uninstall_journal()
286
+ print(json.dumps({"recovered": True, "result": "UNINSTALLED"}, sort_keys=True))
287
+ return 0
288
+
289
+
290
  def run(argv: list[str]) -> subprocess.CompletedProcess[str]:
291
  return subprocess.run(argv, capture_output=True, text=True, check=False, timeout=60)
292
 
 
392
 
393
 
394
  def uninstall() -> int:
395
+ if UNINSTALL_JOURNAL.exists() or UNINSTALL_JOURNAL.is_symlink():
396
+ return recover_uninstall()
397
  manifest_path = STATE / "install-manifest.json"
398
  if manifest_path.is_symlink() or not manifest_path.is_file():
399
  raise SystemExit("installed manifest is missing")
400
+ manifest = validate_manifest_structure(
401
+ json.loads(manifest_path.read_text(encoding="utf-8"))
402
+ )
403
+ validate_remaining_targets(manifest, allow_missing=False)
 
 
 
404
  if not owned_cgroups_empty() or not quarantine_empty():
405
  raise SystemExit("refusing uninstall with populated or uncertain Eggcracker cgroups")
406
+ workload_gid = write_uninstall_journal(manifest)
407
  supervisor_stopped = False
408
  watchdog_stopped = False
409
  try:
 
419
  raise SystemExit("refusing uninstall because cgroups remained populated after stop")
420
  reset_failed(SUPERVISOR)
421
  reset_failed(WATCHDOG)
422
+ for path in TARGETS:
423
  if path.exists() and not path.is_symlink():
424
  shutil.rmtree(path) if path.is_dir() else path.unlink()
425
+ remove_manifest_identity(manifest, workload_gid)
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  require_success(["/usr/bin/systemctl", "daemon-reload"])
427
  # Removing the unit files can leave transient ``not-found`` objects in
428
  # the manager. A global reset after the daemon reload lets systemd
429
  # garbage-collect them. Naming a removed unit here would recreate the
430
  # very not-found object the uninstall verifier rejects.
431
  require_success(["/usr/bin/systemctl", "reset-failed"])
432
+ remove_uninstall_journal()
433
  except BaseException:
434
  # A refused or interrupted transaction must not leave protection
435
  # disabled. Best-effort restoration is deliberately attempted for
scripts/verify_uninstalled.py CHANGED
@@ -32,6 +32,7 @@ PATHS = (
32
  Path("/var/lib/lumi-eggcracker"), Path("/run/lumi-eggcracker"),
33
  Path("/run/lumi-eggcracker-watchdog"),
34
  Path("/var/lib/lumi-eggcracker-install-journal.json"),
 
35
  Path("/run/lock/lumi-eggcracker-lifecycle.lock"),
36
  )
37
 
 
32
  Path("/var/lib/lumi-eggcracker"), Path("/run/lumi-eggcracker"),
33
  Path("/run/lumi-eggcracker-watchdog"),
34
  Path("/var/lib/lumi-eggcracker-install-journal.json"),
35
+ Path("/var/lib/lumi-eggcracker-uninstall-journal.json"),
36
  Path("/run/lock/lumi-eggcracker-lifecycle.lock"),
37
  )
38
 
tests/test_installer_security.py CHANGED
@@ -86,6 +86,9 @@ class InstallerSecurityTests(unittest.TestCase):
86
  lifecycle = (ROOT / "scripts" / name).read_text(encoding="utf-8")
87
  self.assertIn("acquire_lifecycle_lock", lifecycle)
88
  self.assertIn("release_lifecycle_lock", lifecycle)
 
 
 
89
 
90
  def test_install_tracks_cold_boot_network_namespace_runtime(self) -> None:
91
  installer = INSTALLER.read_text(encoding="utf-8")
 
86
  lifecycle = (ROOT / "scripts" / name).read_text(encoding="utf-8")
87
  self.assertIn("acquire_lifecycle_lock", lifecycle)
88
  self.assertIn("release_lifecycle_lock", lifecycle)
89
+ uninstaller = UNINSTALLER.read_text(encoding="utf-8")
90
+ self.assertIn("UNINSTALL_JOURNAL_SCHEMA", uninstaller)
91
+ self.assertIn("recover_uninstall", uninstaller)
92
 
93
  def test_install_tracks_cold_boot_network_namespace_runtime(self) -> None:
94
  installer = INSTALLER.read_text(encoding="utf-8")