package host import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "os" "github.com/carlosframework/platform/internal/hostbox" "github.com/carlosframework/platform/internal/hostguard" "github.com/carlosframework/platform/internal/provision" "github.com/carlosframework/platform/internal/release" "github.com/carlosframework/platform/internal/rootparticipation" "github.com/carlosframework/platform/internal/rootstate" ) type generationInventory struct { Handovers []hostbox.GenerationHandover Retirements []hostbox.RetirementJournal Census rootparticipation.Census Installations []hostguard.FenceView Launches []hostbox.LaunchInventory Payloads []hostbox.GenerationPayload Records []generationRecord Unlaunched map[string]string } type generationCensusReservationsKey struct{} // generationCensusParentKey carries the pid whose direct children the // generation census accepts as this command's own (see generationKernel's // parent). Only journal-migrate sets it. type generationCensusParentKey struct{} func generationCensusParent(ctx context.Context) int { pid, _ := ctx.Value(generationCensusParentKey{}).(int) return pid } type generationReconciler struct { read func(context.Context) (generationInventory, error) kernel func(context.Context) (string, string, error) } func generationInventoryDigest(v any) string { raw, _ := json.Marshal(v) sum := sha256.Sum256(raw) return hex.EncodeToString(sum[:]) } func generationOwner(t hostguard.FenceTarget) release.GenerationOwner { return release.GenerationOwner{Host: t.Host, Incarnation: t.Incarnation, Stamp: t.Stamp, Session: t.Session, Box: t.Box, Enrollment: t.Enrollment, BootID: t.BootID, ControllerID: t.ControllerID} } func generationInstallation(v hostguard.FenceView, t release.GenerationOwner) (hostguard.RootInstallation, error) { in := v.Installation known := in.Incarnation == t.Incarnation && in.Stamp == t.Stamp for _, old := range v.Retired { if old.Incarnation == t.Incarnation && old.Stamp == t.Stamp { known = true } } if !known || in.Host != t.Host || in.Incarnation != t.Incarnation || in.Stamp < t.Stamp || in.Box != t.Box || in.Enrollment != t.Enrollment { return in, os.ErrPermission } in.Stamp = t.Stamp return in, nil } // Callers hold release exclusion through use. Recheck independent sources after // kernel inspection; a certificate never substitutes for the next inspection. func (v generationReconciler) reconcile(ctx context.Context, records []release.GenerationReservation) (release.GenerationEvidence, error) { var zero release.GenerationEvidence if v.read == nil || v.kernel == nil { return zero, os.ErrPermission } before, err := v.read(ctx) if err != nil { return zero, err } c := before.Census if c.Schema != 1 || !c.Complete || c.NeverEnrolled || (c.Pending != "" && !(c.Pending == "acquisition" && ctx.Value(launchRecoveryCensusKey{}) == true)) || c.Migration == 0 || c.Revision == 0 || c.LaunchRevision == 0 || c.Box == "" || c.Enrollment == "" { return zero, os.ErrPermission } installs := map[string]hostguard.FenceView{} for _, view := range before.Installations { in := view.Installation if _, exists := installs[in.Host]; exists || view.Schema != 1 || view.Host != in.Host || in.Box != c.Box || in.Enrollment != c.Enrollment || in.Migration != c.Migration || in.InventoryRevision == 0 || in.Record != provision.RecordKey(in.Account, in.App, in.Host) { return zero, os.ErrPermission } installs[in.Host] = view } if err := generationPayloadBindings(before.Payloads, installs); err != nil { return zero, err } physical, err := generationPhysicalPayloads(ctx, before) if err != nil { return zero, err } if err := generationPayloadFiles(ctx, dataDir(), physical); err != nil { return zero, err } matched := make([]bool, len(records)) hosts := map[string]bool{} for _, launch := range before.Launches { t := generationOwner(launch.Target) if _, err := generationInstallation(installs[t.Host], t); err != nil { return zero, err } hosts[t.Host] = true seen := map[string]bool{} for _, unit := range launch.Reservations { if seen[unit.ID] || unit.ID == "" || !hostbox.SameLaunchOwner(unit.Target, launch.Target) { return zero, os.ErrPermission } seen[unit.ID] = true if !hostbox.IsUnitReservation(unit) { if !launch.WritersClosed || unit.State != "settled" { return zero, os.ErrPermission } continue } count := 0 for i, r := range records { b := r.Binding if b.Target != t || b.Attempt != unit.ID { continue } in, err := generationInstallation(installs[t.Host], t) if err != nil { return zero, err } if matched[i] || b.Binding.Host != in.Host || b.Binding.Account != in.Account || b.Binding.App != in.App || b.Record != in.Record || b.Installation != rootHistoryInstallation(in) || b.ControllerPID != launch.ControllerPID || b.ControllerStart != launch.ProcessStart || b.Inputs != unit.Inputs || b.Invocation != unit.InvocationID || b.Executable.Device != unit.Executable.Device || b.Executable.Inode != unit.Executable.Inode || unit.Group.RelativePath != generationBindingGroup(b) { return zero, os.ErrPermission } if unit.State != hostbox.UnitIntended && unit.State != hostbox.UnitStarted && unit.State != hostbox.UnitSettled { return zero, os.ErrPermission } p := r.Process if p != (release.GenerationProcess{}) && (p.PID != unit.PID || p.Start != unit.ProcessStart || p.Group != unit.Group.RelativePath || p.Invocation != unit.Group.InvocationID || p.GroupIdentity.Device != unit.Group.Device || p.GroupIdentity.Inode != unit.Group.Inode) { return zero, os.ErrPermission } if r.Closed && (!launch.WritersClosed || unit.State != hostbox.UnitSettled) { return zero, os.ErrPermission } matched[i] = true count++ } // A closed legacy launch can predate E2, but kernel inspection must still // exclude its references. An open launch always needs its exact root pin. if count != 1 && !(count == 0 && launch.WritersClosed && unit.State == hostbox.UnitSettled) { return zero, os.ErrPermission } } } for _, view := range before.Installations { if !view.Installation.Empty && !hosts[view.Host] && before.Unlaunched[view.Host] != rootHistoryInstallation(view.Installation) { return zero, os.ErrPermission } } for i, r := range records { if matched[i] { continue } // A pre-intention reservation retains its exact controller journal. in, err := generationInstallation(installs[r.Binding.Target.Host], r.Binding.Target) if err != nil || r.Process != (release.GenerationProcess{}) || r.Binding.Installation != rootHistoryInstallation(in) || r.Binding.Binding.Account != in.Account || r.Binding.Binding.App != in.App || r.Binding.Record != in.Record || !hosts[in.Host] { return zero, os.ErrPermission } pending := 0 for _, launch := range before.Launches { if generationOwner(launch.Target) == r.Binding.Target && launch.ControllerPID == r.Binding.ControllerPID && launch.ProcessStart == r.Binding.ControllerStart { if r.Closed && !launch.WritersClosed { return zero, os.ErrPermission } pending++ } } if pending != 1 { return zero, os.ErrPermission } } snapshotDigest := generationInventoryDigest(before) boot, kernel, err := v.kernel(context.WithValue(ctx, generationCensusReservationsKey{}, records)) if err != nil { return zero, err } decoded, err := hex.DecodeString(kernel) if err != nil || len(decoded) != sha256.Size || hex.EncodeToString(decoded) != kernel || boot == "" { return zero, os.ErrPermission } after, err := v.read(ctx) if err != nil { return zero, err } if err := ctx.Err(); err != nil { return zero, err } if snapshotDigest != generationInventoryDigest(after) { return zero, os.ErrPermission } physical, err = generationPhysicalPayloads(ctx, after) if err != nil { return zero, err } if err := generationPayloadFiles(ctx, dataDir(), physical); err != nil { return zero, err } return release.GenerationEvidence{Box: c.Box, Enrollment: c.Enrollment, Migration: c.Migration, Boot: boot, Installations: generationInventoryDigest([]any{before.Installations, before.Payloads, before.Records, before.Retirements, before.Handovers}), Launches: generationInventoryDigest([]any{c.LaunchRevision, before.Launches}), Kernel: kernel}, nil } func generationPayloadBindings(payloads []hostbox.GenerationPayload, installs map[string]hostguard.FenceView) error { type key struct { host, incarnation string stamp uint64 } seen := map[key]bool{} for _, p := range payloads { in := p.Inventory view, ok := installs[in.Host] captured := hostguard.Captured{Incarnation: in.Incarnation, Stamp: in.InstallationStamp} current := captured.Incarnation == view.Installation.Incarnation && captured.Stamp == view.Installation.Stamp known := current for _, old := range view.Retired { known = known || old == captured } k := key{in.Host, in.Incarnation, in.InstallationStamp} if !ok || !known || seen[k] || !in.Complete || p.Revision == 0 || in.Box != view.Installation.Box || in.Enrollment != view.Installation.Enrollment || in.DirectoryRevision == "" { return os.ErrPermission } if current && (p.Revision != view.Installation.InventoryRevision || view.Installation.Empty != (len(in.Entries) == 0)) { return os.ErrPermission } for _, entry := range in.Entries { if entry.Materialization != "materialized" && !(entry.Kind == "timer" && entry.Materialization == "intended") { return os.ErrPermission } } seen[k] = true } for host, view := range installs { in := view.Installation if !seen[key{host, in.Incarnation, in.Stamp}] { return os.ErrPermission } // Rebind preserves predecessor payload obligations. A current empty // installation cannot erase the inventory of an older retained stamp. for _, old := range view.Retired { if !seen[key{host, old.Incarnation, old.Stamp}] { return os.ErrPermission } } } return nil } func productionGenerationInventory(ctx context.Context) (generationInventory, error) { return readProductionGenerationInventory(ctx, false) } func productionLocalGenerationInventory(ctx context.Context) (generationInventory, error) { return readProductionGenerationInventory(ctx, true) } func readProductionGenerationInventory(ctx context.Context, local bool) (generationInventory, error) { snapshot, err := generationInventoryAt(ctx, rootparticipation.Namespace, "/var/lib/carlos-claims/authority/fences", "/var/lib/carlos-claims/journals.db") if err != nil { return generationInventory{}, err } snapshot.Handovers, err = productionGenerationHandovers(ctx) if err != nil { return generationInventory{}, err } snapshot.Retirements, err = productionGenerationRetirements(ctx) if err != nil { return generationInventory{}, err } if len(snapshot.Installations) == 0 { return productionGenerationRegistryInventory(ctx, snapshot) } if local { snapshot, err = generationLocalObligations(ctx, snapshot, productionGenerationCreation) if err != nil { return generationInventory{}, err } return productionGenerationRegistryInventory(ctx, snapshot) } store, err := openDeployStore(ctx) if err != nil { return generationInventory{}, err } snapshot, err = generationRequiredInventory(ctx, store, snapshot, productionGenerationCreation) if err != nil { return generationInventory{}, err } return productionGenerationRegistryInventory(ctx, snapshot) } func generationInventoryAt(ctx context.Context, censusPath, fencesPath, journalPath string) (generationInventory, error) { var out generationInventory censusState, err := rootstate.Open(censusPath, false, false) census := rootparticipation.Ledger{State: censusState} if err != nil { return out, err } defer census.State.Close() if ctx.Value(launchRecoveryCensusKey{}) == true { out.Census, err = census.RecoveryCensus() } else { out.Census, err = census.Census() } if err != nil { return out, err } state, err := rootstate.Open(fencesPath, false, false) if err != nil { return out, err } defer state.Close() out.Installations, err = hostguard.NewRootAuthority(state).GenerationInstallations(ctx) if err != nil { return out, err } journal, err := openGenerationLaunchInventory(journalPath) if err != nil { return out, err } defer journal.Close() out.Launches, err = journal.GenerationLaunches(ctx) if err != nil { return out, err } out.Payloads, err = journal.GenerationPayloads(ctx) return out, err } func openGenerationLaunchInventory(path string) (*hostbox.LaunchJournal, error) { for _, suffix := range []string{"", "-wal", "-shm"} { file, err := rootstate.OpenAuthorityFile(path + suffix) if suffix != "" && errors.Is(err, os.ErrNotExist) { continue } if err != nil { return nil, err } file.Close() } return hostbox.OpenGenerationLaunchReader(path) }