"""Anmeldung und gemeinsame Helfer für alle Backup-Skripte (nur lesender Zugriff). Die Anmeldung läuft per App-Registrierung mit Zertifikat (client credentials). Alle Werte kommen aus Umgebungsvariablen, im Code steht keine feste Kennung: M365_TENANT_ID Verzeichnis-ID des Tenants () M365_CLIENT_ID Anwendungs-ID der App-Registrierung () M365_CERT_THUMBPRINT SHA-1-Fingerabdruck des Zertifikats (), hexadezimal M365_CERT_KEY_PATH Pfad zum privaten Schlüssel (PEM); ersatzweise M365_CERT_PATH M365_CERT_PATH Pfad zum Zertifikat (PEM), wird nur von den PowerShell-Skripten gebraucht M365_TENANT_NAME Tenant-Domäne, z. B. contoso.onmicrosoft.com M365_ANCHOR_GUID optional: GUID der System-Mailbox für den Header X-AnchorMailbox M365_COMPLIANCE_HOST Host des Compliance-Endpunkts (nur für die REST-Variante) Die Module requests und jwt (PyJWT, mit cryptography) werden erst beim ersten Zugriff geladen. So laufen `--help` und die Unittests auch ohne Anmeldung. """ import argparse, base64, json, os, re, threading, time, uuid from pathlib import Path GRAPH_SCOPE = "https://graph.microsoft.com/.default" GRAPH_V1 = "https://graph.microsoft.com/v1.0" GRAPH_BETA = "https://graph.microsoft.com/beta" RETRY_CODES = (429, 500, 502, 503, 504) class ConfigError(Exception): """Eine nötige Umgebungsvariable fehlt.""" class InvokeError(Exception): """Ein Exchange- oder Compliance-Cmdlet ist fehlgeschlagen.""" def env(name, required=True, default=None): value = os.environ.get(name, default) if required and not value: raise ConfigError(f"environment variable {name} is not set") return value def tenant_prefix(): """Teil vor .onmicrosoft.com, z. B. 'contoso'.""" return env("M365_TENANT_NAME").split(".")[0] _tokens = {} def token(scope=GRAPH_SCOPE): """Zugriffstoken für einen Scope, mit Zertifikat-JWT (RS256) geholt und zwischengespeichert.""" cached = _tokens.get(scope) if cached and time.time() - cached[1] < 2400: return cached[0] import jwt, requests # erst hier laden, damit --help ohne Pakete läuft tenant, client = env("M365_TENANT_ID"), env("M365_CLIENT_ID") x5t = base64.urlsafe_b64encode(bytes.fromhex(env("M365_CERT_THUMBPRINT"))).decode().rstrip("=") key_path = env("M365_CERT_KEY_PATH", required=False) or env("M365_CERT_PATH") now = int(time.time()) url = f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token" assertion = jwt.encode({"aud": url, "iss": client, "sub": client, "jti": str(uuid.uuid4()), "nbf": now, "exp": now + 600}, Path(key_path).read_text(), algorithm="RS256", headers={"x5t": x5t}) r = requests.post(url, data={ "client_id": client, "grant_type": "client_credentials", "scope": scope, "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", "client_assertion": assertion}, timeout=30) j = r.json() if "access_token" not in j: raise RuntimeError(f"sign-in failed: {j.get('error')}: {str(j.get('error_description', ''))[:150]}") _tokens[scope] = (j["access_token"], time.time()) return j["access_token"] def g(method, path, scope=GRAPH_SCOPE, **kw): """Graph-Aufruf mit Wiederholung bei 429/5xx und Verbindungsfehlern. Gibt die Response zurück.""" import requests url = path if path.startswith("http") else GRAPH_V1 + path extra = kw.pop("headers", {}) r = None for attempt in range(8): try: r = requests.request(method, url, headers={"Authorization": "Bearer " + token(scope), **extra}, timeout=60, **kw) except requests.RequestException: time.sleep(5 * (attempt + 1)) continue if r.status_code not in RETRY_CODES: return r time.sleep(min(int(r.headers.get("Retry-After", 5 * (attempt + 1))), 120) + 1) if r is None: raise RuntimeError("Graph is not reachable") return r def get_all(path, beta=False): """GET mit Paging. Gibt (liste, None) oder (teilliste, 'status text') zurück. Liefert der Endpunkt ein Einzelobjekt (ohne 'value'), kommt es als Liste mit einem Element.""" out = [] url = path if path.startswith("http") else (GRAPH_BETA if beta else GRAPH_V1) + path while url: r = g("GET", url) if r.status_code != 200: return out, f"{r.status_code} {r.text[:300]}" try: j = r.json() except Exception: return out, f"{r.status_code} no JSON answer (empty)" if "value" not in j: return [j], None out += j["value"] url = j.get("@odata.nextLink") return out, None def invoke(cmd, params=None, host="outlook.office365.com", scope=None, anchor=None): """Ein Get-Cmdlet über die Exchange-Admin-REST-Schnittstelle, mit Paging. Gibt eine Liste zurück. Nur Get-Cmdlets sind erlaubt (Sicherung gegen versehentliche Änderungen).""" import requests assert cmd.startswith("Get-"), cmd tenant = env("M365_TENANT_ID") scope = scope or f"https://{host}/.default" url = f"https://{host}/adminapi/beta/{tenant}/InvokeCommand" guid = env("M365_ANCHOR_GUID", required=False) anchor = anchor or (f"APP:SystemMailbox{{{guid}}}@{tenant}" if guid else None) out = [] body = {"CmdletInput": {"CmdletName": cmd, "Parameters": params or {}}} while url: for attempt in range(4): headers = {"Authorization": "Bearer " + token(scope), "Content-Type": "application/json", "Prefer": "odata.maxpagesize=1000", "Accept-Encoding": "identity"} if anchor: headers["X-AnchorMailbox"] = anchor r = requests.post(url, json=body, timeout=300, headers=headers) if r.status_code in (429, 502, 503, 504): time.sleep(5 * (attempt + 1)) continue break if r.status_code != 200: try: message = r.json()["error"]["message"] except Exception: message = r.text raise InvokeError(f"HTTP {r.status_code}: {message[:400]}") j = r.json() out += j.get("value", []) url = j.get("@odata.nextLink") return out # ---------------------------------------------------------------- gemeinsame Helfer _lock = threading.Lock() def log(out_dir, text, area=""): """Zeile in /backup.log anhängen (threadsicher).""" with _lock: with open(os.path.join(out_dir, "backup.log"), "a") as f: f.write(time.strftime("%H:%M:%S ") + (f"[{area}] " if area else "") + text + "\n") def safe_name(s): """Dateisystem-sicherer Name (höchstens 80 Zeichen).""" return re.sub(r"[^A-Za-z0-9._@-]+", "_", s or "x")[:80] def write_json(path, obj): """JSON atomar schreiben (erst .tmp, dann ersetzen).""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(obj, f, ensure_ascii=False, indent=1, default=str) os.replace(tmp, path) def read_users(out_dir): """Benutzerliste aus dem Graph-Export (graph/users.json im Zielordner).""" with open(os.path.join(out_dir, "graph", "users.json")) as f: return json.load(f) def folder_size(path): """(Anzahl Dateien, Summe Bytes) unter einem Ordner.""" n = total = 0 for d, _, files in os.walk(path): for name in files: n += 1 total += os.path.getsize(os.path.join(d, name)) return n, total def make_parser(description): """Gemeinsamer Argumentparser: --out ist der Zielordner des Backups.""" p = argparse.ArgumentParser(description=description) p.add_argument("--out", required=True, help="backup target folder (read-only access to the tenant)") return p