#!/usr/bin/env python3 """Restore-Hilfe für Secrets: Kennwörter, App-Secrets und Zertifikate. Ein Backup enthält keine Secret-Werte. Dieses Skript liest den Plan aus dem Backup, legt im ZIEL-Tenant neue Secrets an und sichert die neuen Werte in einem Speicher (Datei mit Rechten 600, optional Azure Key Vault). Die nicht gesicherten Kennwörter und Secret-Werte werden interaktiv abgefragt (getpass, Eingabe unsichtbar). Ohne --execute gibt es nur einen Trockenlauf (kein Netz, keine Änderung). Nur Standardbibliothek plus requests. Werte erscheinen nie in Log, Journal oder Ausgabe. """ import argparse, base64, getpass, hashlib, json, os, re, secrets, string, subprocess import sys, tempfile, time, unittest, uuid from datetime import datetime, timezone, timedelta from pathlib import Path PROGRESS_DEFAULT = "restore_secrets_progress.json" STORE_DEFAULT = "restore_secrets_store.json" GUID = re.compile(r"^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$") # ----------------------------------------------------------------- Hilfen def now(): return datetime.now(timezone.utc) def iso(d): return d.strftime("%Y-%m-%dT%H:%M:%SZ") def load_json(path, default): p = Path(path) if not p.exists(): return default return json.loads(p.read_text(encoding="utf-8")) def write_600(path, data): """Atomar mit Rechten 600 schreiben (die Datei ist nie für andere lesbar).""" p = Path(path); tmp = p.with_name(p.name + ".tmp") fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(data, f, indent=1, ensure_ascii=False) os.chmod(tmp, 0o600); os.replace(tmp, p) # ---------------------------------------------------------- Kennwortregeln def check_password(pw, upn=""): """Gibt die Liste der Verstösse zurück (leer = in Ordnung). Strenger als Entra (8-256, 3 von 4 Klassen).""" f = [] if len(pw) < 12: f.append("at least 12 characters") if len(pw) > 256: f.append("at most 256 characters") classes = sum([any(c.islower() for c in pw), any(c.isupper() for c in pw), any(c.isdigit() for c in pw), any(not c.isalnum() and c.isascii() for c in pw)]) if classes < 3: f.append("at least 3 of 4: upper case, lower case, digits, special characters") if pw != pw.strip(): f.append("no space at the start or end") if not pw.isascii(): f.append("ASCII characters only") local = upn.split("@")[0].lower() if len(local) >= 3 and local in pw.lower(): f.append("must not contain the user name") return f def random_password(length=20): chars = string.ascii_letters + string.digits + "!#$%&*+-=?@_" while True: pw = "".join(secrets.choice(chars) for _ in range(length)) if not check_password(pw) and all(any(c in s for c in pw) for s in (string.ascii_lowercase, string.ascii_uppercase, string.digits, "!#$%&*+-=?@_")): return pw def map_upn(upn, new_domain=None): """UPN im Zieltenant: Domäne ersetzen (Option --new-domain), sonst unverändert.""" if not new_domain or "@" not in upn: return upn return upn.rsplit("@", 1)[0] + "@" + new_domain.lstrip("@") # ------------------------------------------------------------------- Plan def read_inventory(backup): """Inventar der Secrets lesen (secrets_inventory.json im Backup-Ordner).""" f = Path(backup) / "secrets_inventory.json" return json.loads(f.read_text(encoding="utf-8")) if f.exists() else [] def read_plan(backup): b = Path(backup); g = b / "graph" def j(name, default): p = g / name return json.loads(p.read_text(encoding="utf-8")) if p.exists() else default users = j("users.json", []); apps = j("applications.json", []); sps = j("servicePrincipals.json", []) inventory = read_inventory(backup) plan = {"users": [], "app_secrets": [], "app_certificates": [], "sp_credentials": [], "notes": []} guests = synced = 0 for u in users: upn = u.get("userPrincipalName", "") if u.get("userType") == "Guest" or "#EXT#" in upn: guests += 1; continue if u.get("onPremisesSyncEnabled"): synced += 1; continue plan["users"].append({"id": u["id"], "upn": upn, "name": u.get("displayName", "")}) def collect(objs, kind, target_pw, target_key): for o in objs: for k in o.get("passwordCredentials") or []: target_pw.append({"objectId": o["id"], "appId": o.get("appId"), "app": o.get("displayName"), "keyId": k.get("keyId"), "display_name": k.get("displayName") or "", "expires": k.get("endDateTime"), "type": kind}) for k in o.get("keyCredentials") or []: target_key.append({"objectId": o["id"], "appId": o.get("appId"), "app": o.get("displayName"), "keyId": k.get("keyId"), "display_name": k.get("displayName") or "", "expires": k.get("endDateTime"), "usage": k.get("usage"), "key_type": k.get("type"), "type": kind}) collect(apps, "application", plan["app_secrets"], plan["app_certificates"]) collect(sps, "servicePrincipal", plan["sp_credentials"], plan["sp_credentials"]) for e in plan["sp_credentials"]: e.setdefault("kind", "Certificate" if "usage" in e else "Secret") # Inventar nur zum Abgleich: Einträge, die in graph/ fehlen, ergänzen known = {(e["objectId"], e["keyId"]) for k in ("app_secrets", "app_certificates", "sp_credentials") for e in plan[k]} missing = 0 for e in inventory: if (e.get("objectId"), e.get("keyId")) in known: continue missing += 1 kind = e.get("kind") or "" entry = {"objectId": e.get("objectId"), "appId": e.get("appId"), "app": e.get("app"), "keyId": e.get("keyId"), "display_name": e.get("display_name") or "", "expires": e.get("expires"), "type": "application", "usage": e.get("usage"), "key_type": e.get("key_type")} if e.get("source") == "servicePrincipals": entry["type"] = "servicePrincipal"; plan["sp_credentials"].append(dict(entry, kind=kind)) elif kind.startswith("Secret"): plan["app_secrets"].append(entry) else: plan["app_certificates"].append(entry) plan["_inventory_added"] = missing # Hinweisliste (Checkliste) grants = len(j("oauth2PermissionGrants.json", [])) notes = plan["notes"] def note(i, t): notes.append({"id": i, "text": t}) note("mfa", "MFA methods (Authenticator, FIDO2, phone) and Windows Hello: every person registers again; issue a Temporary Access Pass if needed.") note("break-glass", "Emergency accounts (break glass): set a long password of their own, store it offline in a safe, test the sign-in.") if guests: note("guests", f"{guests} guest account(s) are not set: invite them again in the target tenant.") if synced: note("sync", f"{synced} synchronized account(s): the password comes from the local AD (Entra Connect), do not set it.") if grants: note("consent", f"{grants} permission grant(s) (oauth2PermissionGrants): grant admin consent per app again in the target tenant; afterwards replace the app secrets in the systems that use them.") note("consumers", "Update every system that needs a new app secret or certificate (scripts, pipelines, services) with the new values.") note("connections", "Re-authenticate connections/connectors (Power Automate, Logic Apps, Power Apps, Teams connectors, webhooks); connections belong to people and are not backed up.") note("service-accounts", "Enter service accounts and passwords in scripts, task scheduler, automation runbooks, pipelines and configurations (for example M365DSC, Exchange automation).") note("exchange", "Exchange Online: create a new certificate for the automation app (app-only) and store it in the script; check SMTP relay, connectors and app passwords.") note("sharepoint", "SharePoint/Teams: set up sharing links, webhooks and service accounts for synchronization (for example Intune, third parties) again.") note("sspr", "Self-service password reset: let people register their contact data and methods again.") note("mail-oauth", "Third-party applications with SAML/SSO (Salesforce, Box, LinkedIn and so on): link certificates and secrets in the third-party system again.") note("licenses", "Assign licenses before the first sign-in, otherwise mailbox and services are missing.") return plan def print_plan(plan, out=print): out("== Plan: places that need a secret ==") out(f"(a) user passwords : {len(plan['users'])}") out(f"(b) app secrets : {len(plan['app_secrets'])}") out(f"(c) app certificates : {len(plan['app_certificates'])}") out(f"(d) service principal credentials : {len(plan['sp_credentials'])}") out(f"(e) notes (checklist, manual) : {len(plan['notes'])}") if plan.get("_inventory_added"): out(f" (added from the secrets inventory: {plan['_inventory_added']})") out("\n(a) Users:") for u in plan["users"]: out(f" - {u['upn']} ({u['name']})") for t, n in (("b", "app_secrets"), ("c", "app_certificates"), ("d", "sp_credentials")): out(f"\n({t}) {n}:") for e in plan[n]: out(f" - {e['app']} [{e['type']}] {e.get('kind') or ''} '{e['display_name']}' keyId={e['keyId']} expires={e['expires']}") out("\n(e) Checklist:") for h in plan["notes"]: out(f" [ ] {h['text']}") # ------------------------------------------------------------- Journal PROGRESS_FIELDS = ("id", "category", "object", "kind", "expires", "keyId", "time", "status") class Progress: """Hält nur Felder der Whitelist; Werte können gar nicht hineingelangen.""" def __init__(self, path): self.path = Path(path) self.d = load_json(path, {"version": 1, "entries": [], "checklist": {}}) def done(self, eid): return any(e["id"] == eid and e["status"] == "ok" for e in self.d["entries"]) def add(self, **kw): e = {k: kw.get(k) for k in PROGRESS_FIELDS}; e["time"] = iso(now()) self.d["entries"] = [x for x in self.d["entries"] if x["id"] != e["id"]] + [e] self.save() def save(self): write_600(self.path, self.d) # ----------------------------------------------------------------- Speicher class Store: """Neue Werte: Datei (600), Bildschirm (einmalig am Ende) und/oder Key Vault.""" def __init__(self, mode, path, kv=None): self.mode, self.path, self.kv = mode, Path(path), kv self.screen = {} self.file = load_json(path, {}) if mode == "file" else {} def put(self, name, value, meta): if self.mode == "file": self.file[name] = dict(meta, value=value); write_600(self.path, self.file) else: self.screen[name] = dict(meta, value=value) if self.kv: self.kv(name, value, meta) def finish(self, interactive): if self.mode == "file" and self.file: print(f"\nNew values are stored in {self.path} (permissions 600).") print("IMPORTANT: move them into a password manager or Azure Key Vault, then DELETE the file (shred -u).") if self.mode == "screen" and self.screen: if interactive and input("\nShow the new values ONCE on screen now? (y/n) ").strip().lower() == "y": for k, v in self.screen.items(): print(f" {k}: {v['value']}") print("Save them now; they are not shown again.") else: print("Values were not shown and are lost (mode screen).") # ------------------------------------------------------------------ Graph class RestoreError(Exception): pass class Target: """Zugang zum ZIEL-Tenant. Wird nur im Ausführungsmodus benutzt.""" def __init__(self, tenant, client_id, live): self.tenant, self.client_id, self.live = tenant, client_id, live self._t = {} def _assertion(self, pem, key): der = subprocess.run(["openssl", "x509", "-in", pem, "-outform", "DER"], capture_output=True, check=True).stdout x5t = base64.urlsafe_b64encode(hashlib.sha1(der).digest()).rstrip(b"=").decode() b64 = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=") aud = f"https://login.microsoftonline.com/{self.tenant}/oauth2/v2.0/token" head = b64(json.dumps({"alg": "RS256", "typ": "JWT", "x5t": x5t}).encode()) n = int(time.time()) body = b64(json.dumps({"aud": aud, "iss": self.client_id, "sub": self.client_id, "jti": str(uuid.uuid4()), "nbf": n, "exp": n + 600}).encode()) raw = head + b"." + body sig = subprocess.run(["openssl", "dgst", "-sha256", "-sign", key], input=raw, capture_output=True, check=True).stdout return (raw + b"." + b64(sig)).decode() def token(self, scope): import requests if not self.live: raise RestoreError("network access is blocked in dry-run mode") t = self._t.get(scope) if t and time.time() < t[1]: return t[0] data = {"client_id": self.client_id, "grant_type": "client_credentials", "scope": scope} pem, key = os.environ.get("M365_TARGET_CERT_PEM"), os.environ.get("M365_TARGET_CERT_KEY") if pem and key: data.update(client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion=self._assertion(pem, key)) else: sec = os.environ.get("M365_TARGET_CLIENT_SECRET") or getpass.getpass("Client secret of the target tenant (input is hidden): ") os.environ["M365_TARGET_CLIENT_SECRET"] = sec # nur im eigenen Prozess; nie ausgegeben data["client_secret"] = sec r = requests.post(f"https://login.microsoftonline.com/{self.tenant}/oauth2/v2.0/token", data=data, timeout=30) j = r.json() if "access_token" not in j: raise RestoreError(f"sign-in failed: {j.get('error')} {str(j.get('error_description', ''))[:120]}") self._t[scope] = (j["access_token"], time.time() + int(j.get("expires_in", 3000)) - 120) return j["access_token"] def g(self, method, path, scope="https://graph.microsoft.com/.default", **kw): import requests url = path if path.startswith("http") else "https://graph.microsoft.com/v1.0" + path r = None for v in range(6): try: r = requests.request(method, url, headers={"Authorization": "Bearer " + self.token(scope)}, timeout=60, **kw) except requests.RequestException: time.sleep(3 * (v + 1)); continue if r.status_code not in (429, 500, 502, 503, 504): return r time.sleep(min(int(r.headers.get("Retry-After", 3 * (v + 1))), 60)) if r is None: raise RestoreError("Graph is not reachable") return r def find(self, kind, name=None, object_id=None): """Objekt im Ziel finden; gibt ein dict mit id oder None zurück.""" if object_id: r = self.g("GET", f"/{kind}/{object_id}") return r.json() if r.status_code == 200 else None q = name.replace("'", "''") r = self.g("GET", f"/{kind}?$filter=displayName eq '{q}'&$select=id,displayName,appId,keyCredentials") if r.status_code != 200: raise RestoreError(f"search {kind} '{name}': HTTP {r.status_code}") v = r.json().get("value", []) if len(v) > 1: raise RestoreError(f"'{name}' is not unique in the target ({len(v)} hits); use --app-mapping") return v[0] if v else None def keyvault_store(target, vault_name): def f(name, value, meta): sn = re.sub(r"[^0-9A-Za-z-]", "-", name)[:127] r = target.g("PUT", f"https://{vault_name}.vault.azure.net/secrets/{sn}?api-version=7.4", scope="https://vault.azure.net/.default", json={"value": value, "attributes": {"enabled": True}, "tags": {"source": "secrets_restore"}}) if r.status_code not in (200, 201): raise RestoreError(f"Key Vault '{sn}': HTTP {r.status_code}") return f # ------------------------------------------------------------- Zertifikate def new_cert(app, days, folder): """Selbstsigniertes Zertifikat per openssl; privater Schlüssel mit Rechten 600. Gibt (b64_der, key_path, end) zurück.""" folder = Path(folder); folder.mkdir(parents=True, exist_ok=True) os.chmod(folder, 0o700) stem = re.sub(r"[^0-9A-Za-z_-]", "_", app) + "_" + uuid.uuid4().hex[:8] key, crt = folder / (stem + ".key"), folder / (stem + ".crt") old = os.umask(0o077) try: subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), "-out", str(crt), "-days", str(days), "-subj", "/CN=" + re.sub(r"[^0-9A-Za-z _.-]", "", app)], capture_output=True, check=True) finally: os.umask(old) os.chmod(key, 0o600) return cert_b64(crt), str(key), now() + timedelta(days=days) def cert_b64(path): raw = Path(path).read_bytes() form = "PEM" if b"-----BEGIN" in raw else "DER" der = subprocess.run(["openssl", "x509", "-inform", form, "-in", str(path), "-outform", "DER"], capture_output=True, check=True).stdout return base64.b64encode(der).decode() # ------------------------------------------------------------------ Eingabe def ask(text, allowed, default=None): while True: a = input(text).strip().lower() or (default or "") if a in allowed: return a print(" Please enter one of:", "/".join(allowed)) def enter_password(upn): """Kennwort zweimal abfragen (getpass, unsichtbar); es wird nie ausgegeben oder protokolliert.""" while True: a = getpass.getpass(f" Password for {upn}: "); b = getpass.getpass(" Again: ") if a != b: print(" The entries differ."); continue f = check_password(a, upn) if f: print(" Too weak: " + "; ".join(f)); continue return a # --------------------------------------------------------------- Ausführung def eid(*parts): return ":".join(str(t) for t in parts) def target_object(target, kind, e, mapping): z = mapping.get(e["appId"]) or mapping.get(e["objectId"]) or mapping.get(e["app"]) if z and GUID.match(z): o = target.find(kind, object_id=z) else: o = target.find(kind, name=z or e["app"]) if not o: raise RestoreError(f"'{e['app']}' not found in the target (use a mapping file or create the app first)") return o def run(args, plan, answers, interactive): live = args.execute target = Target(args.tenant, args.client_id, live) progress = Progress(args.progress_file) kv = keyvault_store(target, args.keyvault) if args.keyvault else None store = Store(args.output, args.store_file, kv) mapping = json.loads(Path(args.app_mapping).read_text(encoding="utf-8")) if args.app_mapping else {} errors = 0 def answer(area, key, default=None): b = answers.get(area, {}) return b.get(key, b.get("default", default)) # ---- Schritt 2: Benutzer print("\n== Step 2: users ==") all_random = args.all_random or answers.get("users", {}).get("default") == "random" for u in plan["users"]: upn = map_upn(u["upn"], args.new_domain); pid = eid("user", upn.lower()) if progress.done(pid): print(f" skipped (done): {upn}"); continue mode = answer("users", u["upn"]) if not mode: if all_random: mode = "random" elif interactive: a = ask(f" {upn}: [r]andom / [e]nter / [a]ll remaining random / [s]kip: ", ("r", "e", "a", "s"), "r") if a == "a": all_random = True; a = "r" mode = {"r": "random", "e": "enter", "s": "skip"}[a] elif not live: mode = "random" # Trockenlauf: nur den Standard anzeigen else: raise RestoreError(f"no decision for {u['upn']} (--answers, --all-random or interactive)") if mode == "skip": print(f" skipped: {upn}"); continue if mode == "enter" and not interactive and not sys.stdin.isatty(): raise RestoreError("password entry needs a terminal") if not live: print(f" [dry run] {upn}: mode {mode}, change at first sign-in"); continue try: t = target.find("users", object_id=upn) if not t: raise RestoreError(f"user {upn} not found in the target") pw = random_password() if mode == "random" else enter_password(upn) r = target.g("PATCH", f"/users/{t['id']}", json={"passwordProfile": {"password": pw, "forceChangePasswordNextSignIn": True}}) if r.status_code not in (200, 204): raise RestoreError(f"PATCH {upn}: HTTP {r.status_code}") store.put(f"user-{upn}", pw, {"kind": "user password", "object": upn}) progress.add(id=pid, category="user", object=upn, kind="password(" + mode + ")", status="ok") print(f" set: {upn}") except RestoreError as e: errors += 1; print(f" ERROR {upn}: {e}") progress.add(id=pid, category="user", object=upn, kind="password", status="error") # ---- Schritt 3: Secrets (Apps und Dienstprinzipale) print("\n== Step 3: app secrets / service principal secrets ==") secret_list = [("applications", e) for e in plan["app_secrets"]] + \ [("servicePrincipals", e) for e in plan["sp_credentials"] if (e.get("kind") or "Secret").startswith("Secret")] for kind, e in secret_list: pid = eid("secret", kind, e["objectId"], e["keyId"]) if progress.done(pid): print(f" skipped (done): {e['app']} '{e['display_name']}'"); continue days = int(answer("app_secrets", e["keyId"]) or answers.get("lifetime_days") or args.lifetime) if interactive and live and not answers.get("app_secrets") and not args.lifetime_fixed: a = input(f" {e['app']} '{e['display_name']}': lifetime in days [{days}]: ").strip() if a.isdigit(): days = int(a) if not 1 <= days <= 730: raise RestoreError("lifetime must be 1 to 730 days") if not live: print(f" [dry run] {kind[:-1]} {e['app']}: new secret '{e['display_name']}', {days} days"); continue try: o = target_object(target, kind, e, mapping) end = now() + timedelta(days=days) r = target.g("POST", f"/{kind}/{o['id']}/addPassword", json={"passwordCredential": { "displayName": e["display_name"] or "restore", "endDateTime": iso(end)}}) if r.status_code not in (200, 201): raise RestoreError(f"addPassword {e['app']}: HTTP {r.status_code}") j = r.json() store.put(f"secret-{e['app']}-{j['keyId'][:8]}", j["secretText"], {"kind": "secret", "object": e["app"], "appId": o.get("appId"), "expires": j.get("endDateTime")}) progress.add(id=pid, category="secret", object=e["app"], kind="secret", expires=j.get("endDateTime"), keyId=j["keyId"], status="ok") print(f" created: {e['app']} '{e['display_name']}' until {j.get('endDateTime')}") except RestoreError as x: errors += 1; print(f" ERROR {e['app']}: {x}") progress.add(id=pid, category="secret", object=e["app"], kind="secret", status="error") # ---- Schritt 4: Zertifikate print("\n== Step 4: certificates ==") certs = [("applications", e) for e in plan["app_certificates"]] + \ [("servicePrincipals", e) for e in plan["sp_credentials"] if not (e.get("kind") or "Secret").startswith("Secret")] for kind, e in certs: pid = eid("cert", kind, e["objectId"], e["keyId"]) if progress.done(pid): print(f" skipped (done): {e['app']} '{e['display_name']}'"); continue a = answer("certificates", e["keyId"]) if not a: if interactive: a = ({"n": "new", "f": "file", "s": "skip"})[ask(f" {e['app']} '{e['display_name']}': [n]ew self-signed / upload [f]ile (.cer/.pem) / [s]kip: ", ("n", "f", "s"), "n")] else: a = "new" path = None if isinstance(a, dict): path = a.get("file"); a = "file" if a == "file" and not path: path = input(" Path of the .cer/.pem file: ").strip() if interactive else None if not path: raise RestoreError("certificate file is missing") if a == "skip": print(f" skipped: {e['app']}"); continue if not live: print(f" [dry run] {e['app']}: attach {'file ' + path if path else 'a new self-signed certificate'}"); continue try: o = target_object(target, kind, e, mapping) if path: b64, key_path, end = cert_b64(path), None, now() + timedelta(days=365) else: b64, key_path, end = new_cert(e["app"], int(answers.get("certificate_days", 365)), args.key_folder) r0 = target.g("GET", f"/{kind}/{o['id']}?$select=keyCredentials") existing = [{k: v for k, v in kc.items() if k in ("customKeyIdentifier", "displayName", "endDateTime", "key", "keyId", "startDateTime", "type", "usage")} for kc in r0.json().get("keyCredentials", [])] if r0.status_code == 200 else [] new = {"type": "AsymmetricX509Cert", "usage": e.get("usage") or "Verify", "key": b64, "displayName": e["display_name"] or "restore", "endDateTime": iso(end), "startDateTime": iso(now())} if not path: # Zeitfenster aus dem Zertifikat lesen ist optional; Graph prüft selbst new.pop("endDateTime"); new.pop("startDateTime") r = target.g("PATCH", f"/{kind}/{o['id']}", json={"keyCredentials": existing + [new]}) if r.status_code not in (200, 204): raise RestoreError(f"PATCH keyCredentials {e['app']}: HTTP {r.status_code}") if key_path: store.put(f"certificate-{e['app']}-{Path(key_path).stem[-8:]}", f"Private key: file {key_path}", {"kind": "certificate", "object": e["app"]}) progress.add(id=pid, category="certificate", object=e["app"], kind="certificate", expires=iso(end), status="ok") print(f" attached: {e['app']} '{e['display_name']}'" + (f" (key: {key_path})" if key_path else "")) except (RestoreError, subprocess.CalledProcessError) as x: errors += 1; print(f" ERROR {e['app']}: {x}") progress.add(id=pid, category="certificate", object=e["app"], kind="certificate", status="error") # ---- Checkliste print("\n== Checklist (manual) ==") done = set(answers.get("checklist_done", [])) | {k for k, v in progress.d.get("checklist", {}).items() if v} for h in plan["notes"]: ok = h["id"] in done if not ok and interactive and live: ok = input(f" {h['text']}\n Done? (y/n) ").strip().lower() == "y" print(f" [{'x' if ok else ' '}] {h['text']}") if live: progress.d.setdefault("checklist", {})[h["id"]] = ok if live: progress.save(); store.finish(interactive) else: print("\nDRY RUN: nothing sent, nothing written. Use --execute to really restore.") return errors # ---------------------------------------------------------------- Selbsttest class Tests(unittest.TestCase): def test_password(self): self.assertTrue(check_password("short1A!")) self.assertTrue(check_password("onlylowercaseletters")) self.assertTrue(check_password("Jane.Doe123x", "jane.doe@example.com")) self.assertFalse(check_password("Good-Password-2026")) for _ in range(50): self.assertFalse(check_password(random_password())) def test_upn(self): self.assertEqual(map_upn("PattiF@contoso.onmicrosoft.com", "new.example"), "PattiF@new.example") self.assertEqual(map_upn("a@b.example"), "a@b.example") self.assertEqual(map_upn("a@b.example", "@c.example"), "a@c.example") def test_progress_without_values(self): with tempfile.TemporaryDirectory() as d: p = Progress(Path(d) / "p.json") value = "S3cr3t-Value-ZZZ-" + secrets.token_hex(8) p.add(id="x", category="secret", object="app", kind="secret", expires="2027", keyId="k", status="ok", value=value, secretText=value) text = (Path(d) / "p.json").read_text() self.assertNotIn(value, text); self.assertNotIn("value", text) self.assertEqual(oct((Path(d) / "p.json").stat().st_mode & 0o777), "0o600") self.assertTrue(Progress(Path(d) / "p.json").done("x")) def test_store_permissions(self): with tempfile.TemporaryDirectory() as d: t = Store("file", Path(d) / "t.json"); t.put("a", "w", {"kind": "x"}) self.assertEqual(oct((Path(d) / "t.json").stat().st_mode & 0o777), "0o600") def test_certificate(self): with tempfile.TemporaryDirectory() as d: b64, key, end = new_cert("Test App", 30, d) self.assertTrue(base64.b64decode(b64)); self.assertEqual(oct(Path(key).stat().st_mode & 0o777), "0o600") def test_dry_run_blocks_network(self): with self.assertRaises(RestoreError): Target("t", "c", False).token("x") def test_inventory(self): with tempfile.TemporaryDirectory() as d: (Path(d) / "secrets_inventory.json").write_text(json.dumps([{"source": "applications", "kind": "Secret"}])) self.assertEqual(read_inventory(d)[0]["kind"], "Secret") self.assertEqual(read_inventory(d + "/missing"), []) def self_test(): r = unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(Tests)) return 0 if r.wasSuccessful() else 1 # -------------------------------------------------------------------- main def main(argv=None): ap = argparse.ArgumentParser(description="Restore helper for secrets: dry run by default, --execute really restores") ap.add_argument("--backup"); ap.add_argument("--tenant"); ap.add_argument("--client-id") ap.add_argument("--execute", action="store_true", help="really restore (otherwise dry run)") ap.add_argument("--new-domain", help="new domain for UPNs in the target tenant") ap.add_argument("--app-mapping", help="JSON: backup app (name/appId/objectId) -> target (name or objectId)") ap.add_argument("--answers", help="JSON with predefined decisions (non-interactive)") ap.add_argument("--all-random", action="store_true", help="random passwords for all users") ap.add_argument("--lifetime", type=int, default=180, help="lifetime of new secrets in days (default 180)") ap.add_argument("--lifetime-fixed", action="store_true", help="do not ask the lifetime per secret") ap.add_argument("--output", choices=("file", "screen"), default="file") ap.add_argument("--store-file", default=STORE_DEFAULT, help="output file for new values (permissions 600)") ap.add_argument("--keyvault", help="name of an Azure Key Vault; also store the values there") ap.add_argument("--key-folder", default="./restore_keys", help="folder for new private keys") ap.add_argument("--progress-file", default=PROGRESS_DEFAULT) ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() for n in ("backup", "tenant", "client_id"): if not getattr(a, n): ap.error(f"--{n.replace('_', '-')} is missing") if not Path(a.backup).is_dir(): ap.error("backup folder not found") plan = read_plan(a.backup) print(f"Backup : {a.backup}\nTarget : {a.tenant} (application {a.client_id})") print("Mode : " + ("EXECUTE" if a.execute else "DRY RUN (default, no network)") + "\n") print_plan(plan) answers = json.loads(Path(a.answers).read_text(encoding="utf-8")) if a.answers else {} interactive = not a.answers and sys.stdin.isatty() and a.execute if a.execute: print("\nNOTE: never copy new values into logs or chats. Sign-in only via environment (M365_TARGET_CLIENT_SECRET or M365_TARGET_CERT_PEM + M365_TARGET_CERT_KEY) or prompt.") if interactive and input("Really restore into the target tenant? (yes/no) ").strip().lower() != "yes": return 1 try: errors = run(a, plan, answers, interactive) except RestoreError as e: print("ABORT:", e); return 2 return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())