chahinebrini 01374c426e feat(supervise-magic): TechLockdown-clone v1 — supervise iPhones without erase
Implementiert eigenen MobileBackup2-Restore-Trick zur Supervision-Übernahme
von aktivierten iOS-Geräten ohne Factory-Reset. Foundation für DiGA-Phase-G
Lock-Layer-Stack (non-removable Apps, non-removable Profiles, OnDemand-VPN-
Toggle-Lock) auf Consumer-iPhones.

Verifiziert end-to-end auf:
- iPhone Air (iPhone18,4, iOS 26.5): TL→ReBreak re-supervise 
- Olfa iPhone 14 Pro (iPhone15,3, iOS 26.4.2): TL→ReBreak re-supervise 

Key empirische Findings:
1. Find-My-iPhone MUSS off sein (ErrorCode 211 sonst)
   → Stolen Device Protection (SDP) zwingt FMI an seit iOS 17.3+
2. SupervisorHostCertificates DARF NICHT in CloudConfigurationDetails sein
   für fresh-supervise auf activated unsupervised devices (sonst partial-apply)
3. MCInstall.SetCloudConfiguration firet 14002 auf allen activated devices
   → MobileBackup2-Restore-Trick ist der einzige Weg
4. TL's extracted-embed-bytes != TL's wire-output (Runtime-Mutation)
   → Verbatim-Kopieren reicht nicht

Reverse-Engineering basiert komplett auf:
- Apple's public protocol docs (devicemanagement, mobilebackup2 schemas)
- libimobiledevice (open-source reference impl)
- TL public-distributed binary (interop-RE, legal per US-DMCA-1201 + EU-2009/24)

Structure:
  cmd/supervise/         — main CLI (check, cloud-config, supervise, cert-info, unsupervise)
  cmd/dump-artifacts/    — diagnostic helper (no device needed)
  cmd/usbmux-proxy/      — MITM-proxy for TL-traffic-capture (debug)
  cmd/tl-patcher/        — patches TL's hard-coded usbmuxd path (debug)
  internal/dlmessage/    — DLMessage wire-protocol (4-byte BE length + plist)
  internal/mobilebackup2/— mobilebackup2-service impl (BaseVersionExchange,
                          Hello, Restore, ServeFiles + TL-extracted templates)
  internal/cloudconfig/  — CloudConfigurationDetails.plist builder (cert-less,
                          25 keys matching TL's runtime-output)
  internal/cert/         — auto-gen + persist supervisor-cert in ~/.rebreak-supervise/
  internal/mcinstall/    — MCInstall.GetCloudConfiguration für state-checks
  internal/device/       — go-ios DeviceEntry wrapper
  internal/afclock/      — AFC sync-lock auf /com.apple.itunes.lock_sync
  internal/notification_proxy/ — PostNotification (syncWillStart/etc)
  internal/preflight/    — FMI/Activation/OS-version pre-checks
  internal/supervise/    — End-to-end Flow-Orchestrierung (MobileBackup2 default,
                          MCInstall via REBREAK_FORCE_MCINSTALL=1)

Pending für volle Productization (Phase G):
- Fresh-supervise direkt-empirisch auf truly-unsupervised iPhone testen
  (heute Nacht nur durch Inferenz aus TL-Verhalten gestützt)
- Auto-MDM-enroll-Step nach Supervise (ConfigurationURL oder cfgutil-style)
- DiGA-Onboarding-Flow + Lyra-Coach für FMI/SDP-Disable
- Multi-Device-Validation (Modelle, iOS-Versionen)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 01:55:10 +02:00

161 lines
5.1 KiB
Go

// Package supervise orchestriert den End-to-End Supervise-Flow.
//
// Auto-routet je nach Device-State:
// - unsupervised → superviseFresh (MCInstall.SetCloudConfiguration)
// - already supervised → SuperviseViaBackup (MobileBackup2.Restore-Trick)
//
// Beide Pfade enden mit Reboot + Verify via MCInstall.GetCloudConfiguration.
package supervise
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"time"
"github.com/raynis/rebreak-supervise-magic/internal/cert"
"github.com/raynis/rebreak-supervise-magic/internal/device"
"github.com/raynis/rebreak-supervise-magic/internal/mcinstall"
)
// Options steuert die Variation.
type Options struct {
OrgName string
DryRun bool
Verbose bool
BackupPath string // wenn != "", schreibt current cloud-config als JSON dorthin VOR Write
}
// Supervise — Haupt-Entry. Apple's MCInstall.SetCloudConfiguration firet 14002
// auf ALLEN post-activated devices (auch unsupervised — Apple's empty-cloud-config-
// shell zählt schon als "cloud config present"). Daher: immer MobileBackup2-Path.
//
// Auf already-supervised devices ist MobileBackup2 sowieso required (re-supervise).
// Auf unsupervised devices (post factory-reset) ist MobileBackup2 cleaner als
// MCInstall weil clean-state weniger conflicts hat.
func Supervise(udid string, opts Options) error {
// 2026-05-28 ENV-OVERRIDE: REBREAK_FORCE_MCINSTALL=1 zwingt den MCInstall-
// Pfad (statt MobileBackup2). Für Tests auf activated+unsupervised devices
// wo Memory's "14002-Hypothese" empirisch zu validieren ist. Ändert den
// Default-Air-Re-Supervise-Pfad NICHT.
if os.Getenv("REBREAK_FORCE_MCINSTALL") == "1" {
fmt.Printf("[router] FORCE_MCINSTALL=1 → superviseFresh path (MCInstall.SetCloudConfiguration)\n")
return superviseFresh(udid, opts)
}
conn, err := device.Connect(udid)
if err == nil {
isSupervised, _ := conn.IsSupervised()
conn.Close()
if isSupervised {
fmt.Printf("[router] device supervised → MobileBackup2-Restore (re-supervise)\n")
} else {
fmt.Printf("[router] device unsupervised → MobileBackup2-Restore (fresh-supervise)\n")
}
}
return SuperviseViaBackup(udid, opts)
}
// superviseFresh nutzt MCInstall.SetCloudConfiguration für unsupervised Devices.
// Apple's 14002-Check ist hier nicht aktiv (kein existing cloud-config).
func superviseFresh(udid string, opts Options) error {
logf := makeLogger(opts.Verbose)
logf("[fresh-flow] step 1/6: connecting to %s ...", udid)
conn, err := device.Connect(udid)
if err != nil {
return fmt.Errorf("step 1: %w", err)
}
defer conn.Close()
logf("[fresh-flow] step 2/6: loading supervision identity ...")
id, err := cert.LoadOrCreate()
if err != nil {
return fmt.Errorf("step 2: %w", err)
}
logf(" ✓ cert %d bytes", len(id.CertDER))
if opts.DryRun {
logf("[fresh-flow] step 3-6: DRY-RUN — skipping MCInstall + reboot")
return nil
}
logf("[fresh-flow] step 3/6: opening MCInstall ...")
mc, err := mcinstall.Open(conn.Device())
if err != nil {
return fmt.Errorf("step 3: %w", err)
}
logf("[fresh-flow] step 4/6: SetCloudConfiguration ...")
if _, err := mc.Supervise(mcinstall.SuperviseConfig{
OrganizationName: opts.OrgName,
CertDER: id.CertDER,
AllowPairing: true,
}); err != nil {
mc.Close()
return fmt.Errorf("step 4: %w", err)
}
mc.Close()
logf(" ✓ cloud-config set")
logf("[fresh-flow] step 5/6: rebooting ...")
if err := conn.Reboot(); err != nil {
return fmt.Errorf("step 5: %w", err)
}
logf("[fresh-flow] step 6/6: waiting + verifying ...")
conn2, err := device.WaitForReconnect(udid, 90*time.Second)
if err != nil {
return fmt.Errorf("step 6: reconnect: %w", err)
}
defer conn2.Close()
logf(" ✓ device back online — DONE")
return nil
}
// Unsupervise — reverse-Flow. Aktuell only via MCInstall path implemented
// für unsupervised→supervised reverse. Für TL-supervised → unsupervised
// müssten wir auch den Backup-Pfad nutzen.
func Unsupervise(udid string, opts Options) error {
logf := makeLogger(opts.Verbose)
logf("[unsupervise] device-unsupervise nicht implementiert in dieser Phase.")
logf("[unsupervise] Manuell: Apple Configurator 2 → iPhone → Profile → Remove.")
return errors.New("unsupervise: not implemented (Phase 2 — falls relevant)")
}
func backupCurrentConfig(conn *device.Conn, path string, logf func(string, ...any)) error {
mc, err := mcinstall.Open(conn.Device())
if err != nil {
return err
}
defer mc.Close()
if err := mc.HelloHostIdentifier(); err != nil {
return err
}
curr, err := mc.GetCloudConfiguration()
if err != nil || curr == nil {
return fmt.Errorf("no existing config")
}
backupBytes, err := json.MarshalIndent(curr, "", " ")
if err != nil {
return err
}
if err := os.WriteFile(path, backupBytes, 0o600); err != nil {
return err
}
logf(" ✓ backed up current cloud-config → %s (%d bytes)", path, len(backupBytes))
return nil
}
func makeLogger(verbose bool) func(format string, args ...any) {
if !verbose {
return func(format string, args ...any) {
fmt.Printf(format+"\n", args...)
}
}
return func(format string, args ...any) {
log.Printf(format, args...)
}
}