system recover: defer a refused census with no journal open; accept a signed deleted exe
carlos-system-recover runs the root generation census to settle the
participation transaction an unfinished apply left open, and the edge's
guard drop-in Requires= it, so every refusal kept the edge down. The
harness box hit two: a short-lived non-root task refused with a bare
"service: permission denied", and the edge still running the
/opt/carlos/carlos the apply had renamed over ("(deleted)", ENOENT).
1. With no journal open the files are whole. On a census box, recover now
defers a refused settlement instead of failing: the transaction, the
reservation and root's update record stay open, so claim acquisitions
stay refused; it logs why and exits 0 so the edge starts. Not retried
at the end of the run. With a journal open, under the apply, and on a
box without a census (ruling 6), recovery fails as before.
2. The service lookup accepts a task whose exe reads "<path> (deleted)"
only when the path is the unit's selected program and the box's
router binary, the image opened through /proc/<pid>/exe is a
root-owned, unlinked regular file no group or other can write, and its
bytes hash to the signed router build of the current or the previous
binary (readRootFloorBinary, the guard's proof). The census's
reference checks still run on the task.
3. Task-level refusals that a later pass can clear (the task exited or
was replaced, or the service lookup refused it) retry with backoff
from 250 ms for at most 20 s, then refuse with the last refusal.
Reference, namespace, mount and structural refusals refuse at once.
4. Each service-lookup refusal names the check, the unit, the cgroup and
the exe link.
The lookup's systemctl, unit-file, proc and signed-binary reads go
through generationServiceEnv so tests can drive it over a fake /proc.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+938
−66
internal/host/guardparticipation_test.go+11 −1internal/host/guardtransaction.go+42 −2internal/host/guardtransaction_test.go+17 −4internal/host/recover_settlement_test.go+187 −0internal/host/rootgeneration_census_linux.go+69 −2internal/host/rootgeneration_census_recover_linux_test.go+389 −0internal/host/rootgeneration_kernel_linux.go+10 −4internal/host/rootgeneration_services_linux.go+193 −47internal/host/systemapply.go+15 −5internal/host/systemparticipation.go+5 −1
diff --git a/internal/host/guardparticipation_test.go b/internal/host/guardparticipation_test.go| index 13746e1b9..59148979c 100644 |
| --- a/internal/host/guardparticipation_test.go |
| +++ b/internal/host/guardparticipation_test.go |
| @@ -92,9 +92,19 @@ func TestSystemGuardRegionHAKeepsFailedCompletionEvidence(t *testing.T) { |
| } |
| } |
| a.settleUpdateBegun(t.Context()) |
| - if err := a.Run(t.Context(), true); err == nil { |
| + err := a.Run(t.Context(), true) |
| + if failure == "controller" { |
| + // No journal is open: recover defers the settlement and |
| + // exits 0 so the edge can start, keeping the evidence. |
| + if err != nil { |
| + t.Fatalf("recover with no journal open = %v, want a deferral that exits 0", err) |
| + } |
| + } else if err == nil { |
| t.Fatal("unsafe recovery succeeded") |
| } |
| + if _, err := os.Stat(filepath.Join(a.floor.Dir, "completed.json")); failure != "completion" && !os.IsNotExist(err) { |
| + t.Fatalf("completion written: %v", err) |
| + } |
| for _, path := range []string{updateBegunPath(a.optDir), evidence} { |
| if _, err := os.Stat(path); err != nil { |
| t.Fatalf("recovery discarded %s: %v", path, err) |
diff --git a/internal/host/guardtransaction.go b/internal/host/guardtransaction.go| index 3a2dacc3b..0af21f519 100644 |
| --- a/internal/host/guardtransaction.go |
| +++ b/internal/host/guardtransaction.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| "github.com/carlosframework/platform/internal/hostactors" |
| execlease "github.com/carlosframework/platform/internal/hostexec" |
| "github.com/carlosframework/platform/internal/hostfloor" |
| @@ -253,7 +254,7 @@ func (a *systemApplier) checkGuardRecovery(ctx context.Context) error { |
| if readErr != nil && !errors.Is(readErr, os.ErrNotExist) { |
| return readErr |
| } |
| - return a.settleGuard(ctx, tx, func() error { return a.controllersRecovered(ctx) }) |
| + return a.settleGuard(ctx, tx, func() error { return a.settleWithoutJournal(ctx) }) |
| } |
| if err != nil { |
| return err |
| @@ -269,7 +270,7 @@ func (a *systemApplier) checkGuardRecovery(ctx context.Context) error { |
| return hostfloor.ErrFloor |
| } |
| if j == nil { |
| - return a.settleGuard(ctx, tx, func() error { return a.controllersRecovered(ctx) }) |
| + return a.settleGuard(ctx, tx, func() error { return a.settleWithoutJournal(ctx) }) |
| } |
| if err := a.controllersRecovered(ctx); err != nil { |
| return err |
| @@ -279,6 +280,45 @@ func (a *systemApplier) checkGuardRecovery(ctx context.Context) error { |
| } |
| return a.guardImage(systemPrevPath(a.optDir)) |
| } |
| + |
| +// errSettlementDeferred marks a settlement that root could not make with |
| +// no journal open. No apply is half done and the files are whole, so |
| +// there is nothing for recovery to restore and no reason to keep the edge |
| +// down (its drop-in Requires= the recover unit). The participation |
| +// transaction stays open, which already refuses every new claim |
| +// acquisition, and the next apply, or recover on the next edge start, |
| +// settles it. Run under --recover logs it and exits 0; the apply returns |
| +// it as before. beginExecutableChange treats the same refusal as a |
| +// deferral (systemparticipation.go). |
| +var errSettlementDeferred = errors.New("participation settlement deferred") |
| + |
| +// settleWithoutJournal is controllersRecovered for the branches with no |
| +// journal open. On a box with root participation (a census), a refusal is |
| +// wrapped in errSettlementDeferred. On a box without one it is returned |
| +// unchanged: those boxes see exactly main's recovery (ruling 6). |
| +func (a *systemApplier) settleWithoutJournal(ctx context.Context) error { |
| + err := a.controllersRecovered(ctx) |
| + if err == nil { |
| + return nil |
| + } |
| + required, checkErr := a.participationDisk().ParticipationRequired(ctx) |
| + if checkErr != nil || !required || ctx.Err() != nil { |
| + return err |
| + } |
| + return fmt.Errorf("%w: no journal is open, so the files are whole; the participation transaction stays open and claim acquisitions stay refused: %w", errSettlementDeferred, err) |
| +} |
| + |
| +// deferSettlement reports whether Run, under --recover, leaves err's |
| +// settlement to a later run instead of failing: only an errSettlementDeferred. |
| +// It logs why. |
| +func (a *systemApplier) deferSettlement(recover bool, err error) bool { |
| + if !recover || !errors.Is(err, errSettlementDeferred) { |
| + return false |
| + } |
| + a.ops.logf("system apply: recover: %v; the edge may start, and the next apply or recover settles it", err) |
| + return true |
| +} |
| + |
| func (a *systemApplier) endGuard(ctx context.Context) error { |
| if !a.guarded() { |
| return nil |
diff --git a/internal/host/guardtransaction_test.go b/internal/host/guardtransaction_test.go| index 310d0e3aa..f0ffc84ec 100644 |
| --- a/internal/host/guardtransaction_test.go |
| +++ b/internal/host/guardtransaction_test.go |
| @@ -270,9 +270,17 @@ func TestGuardRecoveryRefusesControllersAfterBegin(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - if err := a.Run(t.Context(), true); err == nil { |
| + // With a journal open recover still fails, and Requires= |
| + // keeps the edge down. With none, the files are whole: |
| + // recover defers the settlement and exits 0, leaving the |
| + // transaction open. |
| + err = a.Run(t.Context(), true) |
| + if path.journal && err == nil { |
| t.Fatal("unsafe recovery succeeded") |
| } |
| + if !path.journal && err != nil { |
| + t.Fatalf("recover with no journal open = %v, want a deferral that exits 0", err) |
| + } |
| if path.marker { |
| if _, err := os.Stat(marker); err != nil { |
| t.Fatal("marker discarded", err) |
| @@ -413,11 +421,16 @@ func TestPlan9M8GuardRecoveryRecoversPendingWithoutJournal(t *testing.T) { |
| } |
| completed := filepath.Join(a.floor.Dir, "completed.json") |
| if !recovers { |
| - if err == nil { |
| - t.Fatal("a controller that survived recovery was settled") |
| + // No journal is open, so recover defers and exits 0; |
| + // the controller that survived is never settled. |
| + if err != nil { |
| + t.Fatalf("recover with no journal open = %v, want a deferral that exits 0", err) |
| } |
| if _, statErr := os.Stat(completed); !os.IsNotExist(statErr) { |
| - t.Fatal("completion written", statErr) |
| + t.Fatal("a controller that survived recovery was settled", statErr) |
| + } |
| + if _, statErr := os.Stat(marker); path.marker && statErr != nil { |
| + t.Fatal("marker discarded", statErr) |
| } |
| return |
| } |
diff --git a/internal/host/recover_settlement_test.go b/internal/host/recover_settlement_test.go| new file mode 100644 |
| index 000000000..414b9e779 |
| --- /dev/null |
| +++ b/internal/host/recover_settlement_test.go |
| @@ -0,0 +1,187 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// carlos-system-recover runs the root generation census to settle the |
| +// participation transaction an unfinished apply left open. The edge's guard |
| +// drop-in Requires= the recover unit, so a recover that fails keeps the |
| +// edge down. With no journal open the files are whole, so a census refusal |
| +// defers the settlement instead: recover exits 0 with the transaction still |
| +// open. With a journal open it fails as before. |
| + |
| +// refuseCensus makes root's launch census refuse, as the kernel census did |
| +// on the harness box ("service: permission denied"), and stubs the pending |
| +// controller recovery so the refusal is the census's alone. |
| +func refuseCensus(t *testing.T, f *applyFixture) *int { |
| + t.Helper() |
| + calls := 0 |
| + f.a.participation.VerifyLaunches = func(context.Context, uint64) error { |
| + calls++ |
| + return fmt.Errorf("generation census: /proc/1535/task/1535: service: %w", os.ErrPermission) |
| + } |
| + old := recoverPendingControllers |
| + t.Cleanup(func() { recoverPendingControllers = old }) |
| + recoverPendingControllers = func(context.Context, string, string) error { return nil } |
| + return &calls |
| +} |
| + |
| +func logLines(f *applyFixture) *[]string { |
| + var lines []string |
| + logf := f.a.ops.logf |
| + f.a.ops.logf = func(format string, args ...any) { |
| + lines = append(lines, fmt.Sprintf(format, args...)) |
| + logf(format, args...) |
| + } |
| + return &lines |
| +} |
| + |
| +func TestRecoverDefersACensusRefusalWithNoJournalOpen(t *testing.T) { |
| + for _, marker := range []bool{true, false} { |
| + t.Run(map[bool]string{true: "marker", false: "no-marker"}[marker], func(t *testing.T) { |
| + f, id := guardRecoveryFixture(t) |
| + a := f.a |
| + if err := a.floor.Begin(t.Context(), id, a.dataDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + begun := filepath.Join(a.floor.Dir, "update-begun.json") |
| + if !marker { |
| + if err := os.Remove(begun); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + calls := refuseCensus(t, f) |
| + lines := logLines(f) |
| + if err := a.Run(t.Context(), true); err != nil { |
| + t.Fatalf("recover with no journal open = %v, want a deferral that exits 0", err) |
| + } |
| + // Once before root's pending-controller recovery and once after, |
| + // and not again at the end of the run. |
| + if *calls != 2 { |
| + t.Fatalf("recover ran the census %d times, want 2", *calls) |
| + } |
| + // The transaction is still open: no completion, the reservation |
| + // kept, root's update record kept, so acquisitions stay refused. |
| + if _, err := os.Stat(filepath.Join(a.floor.Dir, "completed.json")); !os.IsNotExist(err) { |
| + t.Fatalf("a refused census was settled: %v", err) |
| + } |
| + if _, err := os.Stat(filepath.Join(a.floor.Dir, "activation.json")); err != nil { |
| + t.Fatalf("reservation discarded: %v", err) |
| + } |
| + if _, err := os.Stat(begun); marker && err != nil { |
| + t.Fatalf("marker discarded: %v", err) |
| + } |
| + if got, err := a.participation.UpdateID(); err != nil || got != id { |
| + t.Fatalf("update record = %q, %v; want %s still open", got, err, id) |
| + } |
| + if err := a.participation.Acquire(t.Context(), func() error { return nil }); err == nil { |
| + t.Fatal("a claim acquisition started while the transaction was open") |
| + } |
| + if len(f.calls) != 0 { |
| + t.Fatal("recovery executed a binary or touched a unit", f.calls) |
| + } |
| + if !strings.Contains(strings.Join(*lines, "\n"), "service: permission denied") { |
| + t.Fatalf("the deferral did not log the census's refusal: %q", *lines) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRecoverFailsACensusRefusalWithAJournalOpen(t *testing.T) { |
| + f, id := guardRecoveryFixture(t) |
| + a := f.a |
| + if err := a.floor.Begin(t.Context(), id, a.dataDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := a.journal(systemJournal{Phase: systemPhaseInstalled, Target: "new-build", PrevBuild: "old-build", StartedAt: f.now}); err != nil { |
| + t.Fatal(err) |
| + } |
| + refuseCensus(t, f) |
| + err := a.Run(t.Context(), true) |
| + if err == nil || errors.Is(err, errSettlementDeferred) || !strings.Contains(err.Error(), "service: permission denied") { |
| + t.Fatalf("recover with a journal open = %v, want the census's refusal", err) |
| + } |
| + if _, err := os.Stat(a.file("journal.json")); err != nil { |
| + t.Fatalf("journal discarded: %v", err) |
| + } |
| +} |
| + |
| +func TestRecoverDefersACensusRefusalWithoutAnArmedFloor(t *testing.T) { |
| + // checkUnarmedParticipationRecovery: an apply began root's update |
| + // record and stopped before writing a journal. |
| + f := newApplyFixture(t, "stable", "old") |
| + if f.a.guarded() { |
| + t.Fatal("fixture has an armed floor") |
| + } |
| + if err := f.a.beginExecutableChange(t.Context(), "new", f.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := refuseCensus(t, f) |
| + if err := f.a.Run(t.Context(), true); err != nil { |
| + t.Fatalf("recover with no journal open = %v, want a deferral that exits 0", err) |
| + } |
| + if *calls != 2 { |
| + t.Fatalf("recover ran the census %d times, want 2 (not again to settle the marker)", *calls) |
| + } |
| + if _, err := f.a.participation.UpdateID(); err != nil { |
| + t.Fatalf("recover settled a refused census: %v", err) |
| + } |
| + // With a journal open it still fails. |
| + if err := f.a.journal(systemJournal{Phase: systemPhaseInstalling, Target: "new"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.a.Run(t.Context(), true); err == nil { |
| + t.Fatal("recover with a journal open passed a refused census") |
| + } |
| +} |
| + |
| +func TestApplyStillFailsACensusRefusalWithNoJournalOpen(t *testing.T) { |
| + // Only --recover defers: the apply's own start-up check returns the |
| + // refusal as on main. |
| + f, id := guardRecoveryFixture(t) |
| + if err := f.a.floor.Begin(t.Context(), id, f.a.dataDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + refuseCensus(t, f) |
| + if err := f.a.Run(t.Context(), false); err == nil || !strings.Contains(err.Error(), "service: permission denied") { |
| + t.Fatalf("apply = %v, want the census's refusal", err) |
| + } |
| +} |
| + |
| +func TestRuling6NoCensusRecoverIsUnchanged(t *testing.T) { |
| + // A box without root participation (no census.json) never runs the |
| + // generation census, and a refused settlement fails recover exactly as |
| + // on main: the deferral is for census boxes only. |
| + f, id := guardRecoveryFixture(t) |
| + a := f.a |
| + if err := a.floor.Begin(t.Context(), id, a.dataDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := a.participation.State.Remove("census.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if required, err := a.participationDisk().ParticipationRequired(t.Context()); err != nil || required { |
| + t.Fatalf("fixture still requires participation: %t %v", required, err) |
| + } |
| + a.participation.VerifyLaunches = func(context.Context, uint64) error { |
| + t.Fatal("a no-census box ran the generation census") |
| + return nil |
| + } |
| + if err := os.WriteFile(filepath.Join(a.dataDir, hostexecDir, "host.json"), []byte(`{"state":"pending"}`), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := a.Run(t.Context(), true) |
| + if err == nil || errors.Is(err, errSettlementDeferred) { |
| + t.Fatalf("no-census recover = %v, want main's refusal", err) |
| + } |
| + if _, err := os.Stat(filepath.Join(a.floor.Dir, "completed.json")); !os.IsNotExist(err) { |
| + t.Fatalf("completion written: %v", err) |
| + } |
| +} |
diff --git a/internal/host/rootgeneration_census_linux.go b/internal/host/rootgeneration_census_linux.go| index 8b49b6f0f..57fcdde84 100644 |
| --- a/internal/host/rootgeneration_census_linux.go |
| +++ b/internal/host/rootgeneration_census_linux.go |
| @@ -5,9 +5,11 @@ package host |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "io/fs" |
| "os" |
| "path/filepath" |
| + "time" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/rootstate" |
| @@ -91,13 +93,78 @@ func productionGenerationKernelCensus(ctx context.Context) (string, string, erro |
| }) |
| } |
| +// generationCensusWindow bounds how long the census waits out tasks that |
| +// are still settling: a task that exited or was replaced mid-pass, or one |
| +// the service lookup refused (a unit still activating, the guard's prelude, |
| +// a login's or sshd's short-lived child). A task still refused after it |
| +// refuses the census. |
| +const generationCensusWindow = 20 * time.Second |
| + |
| +// generationTaskRefusal is a census refusal of one task, named by its /proc |
| +// path. Its text is the path and the cause, as before it had a type. |
| +type generationTaskRefusal struct { |
| + task string |
| + err error |
| +} |
| + |
| +func (r *generationTaskRefusal) Error() string { return r.task + ": " + r.err.Error() } |
| + |
| +func (r *generationTaskRefusal) Unwrap() error { return r.err } |
| + |
| +// errGenerationTaskReplaced is a task whose start time moved during its |
| +// inspection: the PID now names another task. It is still a refusal |
| +// (os.ErrPermission), but one a fresh pass can clear. |
| +var errGenerationTaskReplaced = fmt.Errorf("task replaced during the census: %w", os.ErrPermission) |
| + |
| +// transient is true for the task-level refusals a later pass can clear: |
| +// the task exited or was replaced, or the service lookup refused it. A |
| +// task that references a retired generation, or a namespace or mount |
| +// refusal, is not: those refuse at once. |
| +func (r *generationTaskRefusal) transient() bool { |
| + var service *generationServiceRefusal |
| + return errors.Is(r.err, os.ErrNotExist) || errors.Is(r.err, unix.ESRCH) || errors.Is(r.err, errGenerationTaskReplaced) || errors.As(r.err, &service) |
| +} |
| + |
| func generationCensusRetry(ctx context.Context, inspect func() (string, string, error)) (string, string, error) { |
| - for attempt := 0; ; attempt++ { |
| + return generationCensusRetryFor(ctx, inspect, generationCensusWindow, time.Now, generationSleep) |
| +} |
| + |
| +func generationSleep(ctx context.Context, d time.Duration) error { |
| + t := time.NewTimer(d) |
| + defer t.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-t.C: |
| + return nil |
| + } |
| +} |
| + |
| +// generationCensusRetryFor runs whole census passes. A transient task |
| +// refusal is retried with backoff (250 ms, doubling to 4 s) while the next |
| +// wait still ends inside window; then the last refusal is returned as it |
| +// is. Any other missing-file or vanished-process error is retried at once, |
| +// up to three passes, as before. Everything else returns at once. |
| +func generationCensusRetryFor(ctx context.Context, inspect func() (string, string, error), window time.Duration, now func() time.Time, sleep func(context.Context, time.Duration) error) (string, string, error) { |
| + begin, delay, quick := now(), 250*time.Millisecond, 0 |
| + for { |
| if err := ctx.Err(); err != nil { |
| return "", "", err |
| } |
| boot, digest, err := inspect() |
| - if attempt == 2 || (!errors.Is(err, os.ErrNotExist) && !errors.Is(err, unix.ESRCH)) { |
| + if err == nil { |
| + return boot, digest, nil |
| + } |
| + var task *generationTaskRefusal |
| + switch { |
| + case errors.As(err, &task) && task.transient(): |
| + if now().Sub(begin)+delay > window || sleep(ctx, delay) != nil { |
| + return boot, digest, err |
| + } |
| + delay = min(2*delay, 4*time.Second) |
| + case quick < 2 && (errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH)): |
| + quick++ |
| + default: |
| return boot, digest, err |
| } |
| } |
diff --git a/internal/host/rootgeneration_census_recover_linux_test.go b/internal/host/rootgeneration_census_recover_linux_test.go| new file mode 100644 |
| index 000000000..50d163bb1 |
| --- /dev/null |
| +++ b/internal/host/rootgeneration_census_recover_linux_test.go |
| @@ -0,0 +1,389 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The generation census that carlos-system-recover runs, on the two |
| +// refusals the harness box hit: a non-root service still running the |
| +// /opt/carlos/carlos an apply renamed over ("(deleted)"), and short-lived |
| +// tasks the service lookup refused with a bare "permission denied". These |
| +// drive the production service lookup (generationServiceEnv.reader) over a |
| +// fake /proc, replacing only systemctl, the unit files' ownership check, |
| +// the signed-binary proof and the owner uid a non-root test cannot have. |
| + |
| +type deletedExeFixture struct { |
| + generationProcFixture |
| + opt, image string |
| + env generationServiceEnv |
| + current string // digest the env proves for <opt>/carlos |
| + prev string // and for <opt>/carlos.prev; "" is no carlos.prev |
| + execStart string |
| + mainPID string |
| + unit string |
| + tt *testing.T |
| + // deletedName is the exe link's base name; "" is "carlos (deleted)". |
| + deletedName string |
| +} |
| + |
| +func (f *deletedExeFixture) t() *testing.T { return f.tt } |
| + |
| +const deletedExeBody = "carlos router build, now renamed over" |
| + |
| +func deletedExe(t *testing.T) *deletedExeFixture { |
| + t.Helper() |
| + g := generationProc(t) |
| + f := &deletedExeFixture{generationProcFixture: g, opt: filepath.Join(t.TempDir(), "opt", "carlos"), mainPID: "41", unit: "carlos-relay.service"} |
| + if err := os.MkdirAll(f.opt, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.execStart = "{ path=" + f.opt + "/carlos ; argv[]=" + f.opt + "/carlos relay ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=41 ; code=(null) ; status=0/0 }" |
| + generationWrite(t, f.task+"/status", "Tgid:\t41\nUid:\t1001\t1001\t1001\t1001\nKthread:\t0\n") |
| + group := "/system.slice/carlos-relay.service" |
| + generationWrite(t, f.task+"/cgroup", "0::"+group+"\n") |
| + generationWrite(t, f.proc+"/41/cgroup", "0::"+group+"\n") |
| + // The image the task runs: open, then unlinked, as the apply's rename |
| + // leaves the edge's. The exe link reads "<opt>/carlos (deleted)" and |
| + // opens that image, as /proc/<pid>/exe does. |
| + f.image = filepath.Join(t.TempDir(), "image") |
| + f.writeImage(t, deletedExeBody, 0o755, true) |
| + sum := sha256.Sum256([]byte(deletedExeBody)) |
| + f.current = "not-this-build" |
| + f.prev = hex.EncodeToString(sum[:]) |
| + f.env = generationServiceEnv{proc: f.proc, opt: f.opt, owner: uint32(os.Getuid()), |
| + show: func(_ context.Context, unit string) (map[string]string, error) { |
| + if unit != f.unit { |
| + return nil, fmt.Errorf("systemctl show %s: no such unit", unit) |
| + } |
| + return map[string]string{"ControlGroup": group, "MainPID": f.mainPID, "ExecStart": f.execStart, "FragmentPath": "/etc/systemd/system/" + unit}, nil |
| + }, |
| + trust: func(string) error { return nil }, |
| + binary: func(opt, path string) (rootFloorBinary, error) { |
| + switch path { |
| + case filepath.Join(opt, "carlos"): |
| + return rootFloorBinary{Digest: f.current}, nil |
| + case filepath.Join(opt, "carlos.prev"): |
| + if f.prev == "" { |
| + return rootFloorBinary{}, os.ErrNotExist |
| + } |
| + return rootFloorBinary{Digest: f.prev}, nil |
| + } |
| + return rootFloorBinary{}, os.ErrPermission |
| + }, |
| + } |
| + return f |
| +} |
| + |
| +// writeImage replaces the task's image with body at mode, unlinked or not. |
| +func (f *deletedExeFixture) writeImage(t *testing.T, body string, mode os.FileMode, unlink bool) { |
| + t.Helper() |
| + path := f.image + fmt.Sprint(time.Now().UnixNano()) |
| + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(path, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + img, err := os.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { img.Close() }) |
| + if unlink { |
| + if err := os.Remove(path); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + name := f.deletedName |
| + if name == "" { |
| + name = "carlos (deleted)" |
| + } |
| + deleted := filepath.Join(f.opt, name) |
| + os.Remove(deleted) |
| + generationLink(t, fmt.Sprintf("/proc/%d/fd/%d", os.Getpid(), img.Fd()), deleted) |
| + os.Remove(f.task + "/exe") |
| + generationLink(t, deleted, f.task+"/exe") |
| +} |
| + |
| +func (f *deletedExeFixture) census(t *testing.T) error { |
| + t.Helper() |
| + _, err := (generationKernel{proc: f.proc, service: f.env.reader(t.Context())}).absent(t.Context(), f.reservation) |
| + return err |
| +} |
| + |
| +func TestRecoverCensusAcceptsADeletedExeOfTheCurrentOrPreviousBuild(t *testing.T) { |
| + for _, which := range []string{"previous", "current", "current-no-prev"} { |
| + t.Run(which, func(t *testing.T) { |
| + f := deletedExe(t) |
| + switch which { |
| + case "current": |
| + f.current, f.prev = f.prev, "other-build" |
| + case "current-no-prev": |
| + f.current, f.prev = f.prev, "" |
| + } |
| + if err := f.census(t); err != nil { |
| + t.Fatalf("census refused a deleted exe of the %s signed build: %v", which, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRecoverCensusAcceptsTheEdgesDeletedExeInSupervise(t *testing.T) { |
| + // The harness's b2 task: carlos-edge.service's main process, in its |
| + // supervise/ group, still running the pre-apply image, with and |
| + // without the guard drop-in (whose ExecStart is the guard and whose |
| + // selected program is <opt>/carlos). |
| + for _, guarded := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "unguarded", true: "guarded"}[guarded], func(t *testing.T) { |
| + f := deletedExe(t) |
| + f.unit = "carlos-edge.service" |
| + if guarded { |
| + f.execStart = "{ path=/opt/carlos/system/guard/carlos ; argv[]=/opt/carlos/system/guard/carlos system guard-exec edge ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=41 ; code=(null) ; status=0/0 }" |
| + binary := f.env.binary |
| + f.env.binary = func(opt, path string) (rootFloorBinary, error) { |
| + if path == "/opt/carlos/system/guard/carlos" { |
| + return rootFloorBinary{Digest: "guard"}, nil |
| + } |
| + b, err := binary(opt, path) |
| + b.File.Inode = 7 // the live <opt>/carlos, not the deleted image |
| + return b, err |
| + } |
| + } |
| + base := "/system.slice/carlos-edge.service" |
| + generationWrite(t, f.task+"/cgroup", "0::"+base+"/supervise\n") |
| + generationWrite(t, f.proc+"/41/cgroup", "0::"+base+"/supervise\n") |
| + show := f.env.show |
| + f.env.show = func(ctx context.Context, unit string) (map[string]string, error) { |
| + props, err := show(ctx, unit) |
| + if err == nil { |
| + props["ControlGroup"] = base |
| + } |
| + return props, err |
| + } |
| + if err := f.census(t); err != nil { |
| + t.Fatalf("census refused the edge's deleted signed image: %v", err) |
| + } |
| + // The same edge running some other deleted image still refuses. |
| + f.writeImage(t, "an image no identity signs", 0o755, true) |
| + if err := f.census(t); err == nil { |
| + t.Fatal("census accepted an unsigned deleted image in the edge") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRecoverCensusRefusesOtherDeletedExes(t *testing.T) { |
| + for _, attack := range []string{"unsigned", "no-proof", "linked", "group-writable", "not-router-binary", "other-program", "deleted-helper", "other-path"} { |
| + t.Run(attack, func(t *testing.T) { |
| + f := deletedExe(t) |
| + switch attack { |
| + case "unsigned": |
| + f.writeImage(t, "some other build", 0o755, true) |
| + case "no-proof": |
| + f.env.binary = func(string, string) (rootFloorBinary, error) { return rootFloorBinary{}, errRootFloorHistory } |
| + case "linked": |
| + f.writeImage(t, deletedExeBody, 0o755, false) |
| + case "group-writable": |
| + f.writeImage(t, deletedExeBody, 0o775, true) |
| + case "not-router-binary": |
| + // The unit runs another program: a deleted <opt>/carlos is |
| + // not what it selects. |
| + f.execStart = strings.ReplaceAll(f.execStart, f.opt+"/carlos", f.opt+"/helper") |
| + case "other-program": |
| + f.execStart = strings.ReplaceAll(f.execStart, f.opt+"/carlos", "/usr/bin/carlos") |
| + case "other-path": |
| + // The unit selects <opt>/carlos, but the task's image was |
| + // somewhere else when it was deleted. |
| + f.deletedName = "carlos-copy (deleted)" |
| + f.writeImage(t, deletedExeBody, 0o755, true) |
| + case "deleted-helper": |
| + // The unit's own program, deleted, with a signed router |
| + // build's bytes: only <opt>/carlos is ever accepted. |
| + f.execStart = strings.ReplaceAll(f.execStart, f.opt+"/carlos", f.opt+"/helper") |
| + f.deletedName = "helper (deleted)" |
| + f.writeImage(t, deletedExeBody, 0o755, true) |
| + } |
| + err := f.census(t) |
| + if err == nil { |
| + t.Fatalf("%s: census accepted the deleted exe", attack) |
| + } |
| + if !errors.Is(err, os.ErrPermission) && attack != "no-proof" { |
| + t.Fatalf("%s: refusal %v is not a permission refusal", attack, err) |
| + } |
| + if !strings.Contains(err.Error(), "deleted exe check refused") { |
| + t.Fatalf("%s: refusal %q does not name the deleted exe check", attack, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRecoverCensusRefusesADeletedExeNotOwnedByRoot(t *testing.T) { |
| + if os.Getuid() == 0 { |
| + t.Skip("the fixture's image is root-owned when run as root") |
| + } |
| + f := deletedExe(t) |
| + f.env.owner = 0 // production: the image must be root's |
| + if err := f.census(t); err == nil || !strings.Contains(err.Error(), "not an unlinked root-owned file") { |
| + t.Fatalf("census = %v, want a refusal of a non-root-owned image", err) |
| + } |
| +} |
| + |
| +func TestRecoverCensusStillChecksReferencesOfAnAcceptedDeletedExe(t *testing.T) { |
| + for _, ref := range []string{"fd", "mapped", "cwd"} { |
| + t.Run(ref, func(t *testing.T) { |
| + f := deletedExe(t) |
| + b := f.reservation.Binding |
| + switch ref { |
| + case "fd": |
| + generationLink(t, b.Path, f.task+"/fd/3") |
| + case "mapped": |
| + generationWrite(t, f.task+"/maps", fmt.Sprintf("1000-2000 r-xp 0000 %x:%x %d %s\n", generationMajor(b.Executable.Device), generationMinor(b.Executable.Device), b.Executable.Inode, b.Path)) |
| + case "cwd": |
| + generationRelink(t, b.Tree, f.task+"/cwd") |
| + } |
| + if err := f.census(t); err == nil { |
| + t.Fatalf("a deleted-exe task referencing a retired generation (%s) was accepted", ref) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRecoverCensusRefusalsNameCheckUnitCgroupAndExe(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, check, unit, group string |
| + setup func(*deletedExeFixture) |
| + }{ |
| + {"activating", "main pid", "carlos-relay.service", "/system.slice/carlos-relay.service", func(f *deletedExeFixture) { f.mainPID = "0" }}, |
| + {"session", "unit", "session-3.scope", "/user.slice/user-1000.slice/session-3.scope", func(f *deletedExeFixture) { |
| + generationWrite(f.t(), f.task+"/cgroup", "0::/user.slice/user-1000.slice/session-3.scope\n") |
| + }}, |
| + {"live-exe", "exe", "carlos-relay.service", "/system.slice/carlos-relay.service", func(f *deletedExeFixture) { |
| + // A live (not deleted) exe the lookup cannot walk to as a |
| + // root-owned file under the task's root. |
| + generationRelink(f.t(), f.unrelated, f.task+"/exe") |
| + generationRelink(f.t(), "/", f.task+"/root") |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + f := deletedExe(t) |
| + f.tt = t |
| + tc.setup(f) |
| + exe, _ := os.Readlink(f.task + "/exe") |
| + err := f.census(t) |
| + if err == nil { |
| + t.Fatal("census accepted") |
| + } |
| + for _, want := range []string{"/41/task/41: service: " + tc.check, "service: " + tc.check + " check refused", "unit " + tc.unit, "cgroup " + tc.group, "exe " + exe} { |
| + if !strings.Contains(err.Error(), want) { |
| + t.Fatalf("refusal %q does not name %q", err, want) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRecoverCensusRetriesATransientRefusalWithinTheWindow(t *testing.T) { |
| + clock := time.Unix(0, 0) |
| + var slept []time.Duration |
| + now := func() time.Time { return clock } |
| + sleep := func(_ context.Context, d time.Duration) error { |
| + if clock.Sub(time.Unix(0, 0)) > time.Minute { |
| + return errors.New("unbounded retry") // ends a run with no window |
| + } |
| + slept = append(slept, d) |
| + clock = clock.Add(d) |
| + return nil |
| + } |
| + |
| + // A unit still activating, through the real census pass: it clears on |
| + // the fourth pass. |
| + f := deletedExe(t) |
| + passes := 0 |
| + inspect := func() (string, string, error) { |
| + passes++ |
| + f.mainPID = "0" |
| + if passes == 4 { |
| + f.mainPID = "41" |
| + } |
| + _, err := (generationKernel{proc: f.proc, service: f.env.reader(t.Context())}).absent(t.Context(), f.reservation) |
| + return "boot", "digest", err |
| + } |
| + if _, _, err := generationCensusRetryFor(t.Context(), inspect, 20*time.Second, now, sleep); err != nil { |
| + t.Fatalf("a transient refusal did not clear within the window: %v", err) |
| + } |
| + if passes != 4 || fmt.Sprint(slept) != "[250ms 500ms 1s]" { |
| + t.Fatalf("passes=%d slept=%v, want 4 passes after 250ms, 500ms, 1s", passes, slept) |
| + } |
| + |
| + // The same refusal, persistent: refused once the next wait would end |
| + // past the window, with the last pass's refusal. |
| + clock, slept, passes = time.Unix(0, 0), nil, 0 |
| + persistent := func() (string, string, error) { |
| + passes++ |
| + f.mainPID = "0" |
| + _, err := (generationKernel{proc: f.proc, service: f.env.reader(t.Context())}).absent(t.Context(), f.reservation) |
| + return "", "", err |
| + } |
| + _, _, err := generationCensusRetryFor(t.Context(), persistent, 20*time.Second, now, sleep) |
| + if err == nil || !strings.Contains(err.Error(), "main pid check refused") { |
| + t.Fatalf("persistent refusal = %v", err) |
| + } |
| + var total time.Duration |
| + for _, d := range slept { |
| + total += d |
| + } |
| + if total > 20*time.Second || total < 15*time.Second || passes != len(slept)+1 { |
| + t.Fatalf("persistent refusal: %d passes, slept %v (%s), want about 20 s then refuse", passes, slept, total) |
| + } |
| +} |
| + |
| +func TestRecoverCensusRetriesOnlyTaskLevelTransients(t *testing.T) { |
| + sleep := func(context.Context, time.Duration) error { return nil } |
| + for _, tc := range []struct { |
| + name string |
| + err error |
| + retry bool |
| + }{ |
| + {"service", &generationTaskRefusal{task: "/proc/9/task/9", err: fmt.Errorf("service: %w", &generationServiceRefusal{check: "unit", err: os.ErrPermission})}, true}, |
| + {"exited", &generationTaskRefusal{task: "/proc/9/task/9", err: os.ErrNotExist}, true}, |
| + {"replaced", &generationTaskRefusal{task: "/proc/9/task/9", err: errGenerationTaskReplaced}, true}, |
| + {"reference", &generationTaskRefusal{task: "/proc/9/task/9", err: fmt.Errorf("fd: %w", os.ErrPermission)}, false}, |
| + {"mounts", &generationTaskRefusal{task: "/proc/9/task/9", err: fmt.Errorf("mounts: %w", os.ErrPermission)}, false}, |
| + {"structural", os.ErrPermission, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + passes := 0 |
| + _, _, err := generationCensusRetryFor(t.Context(), func() (string, string, error) { |
| + passes++ |
| + if passes == 2 { |
| + return "boot", "digest", nil |
| + } |
| + return "", "", tc.err |
| + }, 20*time.Second, time.Now, sleep) |
| + if tc.retry && (err != nil || passes != 2) { |
| + t.Fatalf("transient %s: passes=%d err=%v", tc.name, passes, err) |
| + } |
| + if !tc.retry && (err == nil || passes != 1) { |
| + t.Fatalf("%s retried: passes=%d err=%v", tc.name, passes, err) |
| + } |
| + }) |
| + } |
| + // A cancelled wait refuses with the refusal it was waiting out. |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + refusal := &generationTaskRefusal{task: "/proc/9/task/9", err: os.ErrNotExist} |
| + _, _, err := generationCensusRetryFor(ctx, func() (string, string, error) { return "", "", refusal }, 20*time.Second, time.Now, func(context.Context, time.Duration) error { cancel(); return context.Canceled }) |
| + if !errors.Is(err, refusal) { |
| + t.Fatalf("cancelled wait = %v", err) |
| + } |
| +} |
diff --git a/internal/host/rootgeneration_kernel_linux.go b/internal/host/rootgeneration_kernel_linux.go| index ea3e73966..03a3209b1 100644 |
| --- a/internal/host/rootgeneration_kernel_linux.go |
| +++ b/internal/host/rootgeneration_kernel_linux.go |
| @@ -366,9 +366,12 @@ func (k generationKernel) task(ctx context.Context, path string, b release.Gener |
| return "", err |
| } |
| end, err := generationStart(again) |
| - if err != nil || end != start { |
| + if err != nil { |
| return "", os.ErrPermission |
| } |
| + if end != start { |
| + return "", errGenerationTaskReplaced |
| + } |
| return start, nil |
| } |
| } |
| @@ -424,9 +427,12 @@ func (k generationKernel) task(ctx context.Context, path string, b release.Gener |
| return "", err |
| } |
| again, err := generationStart(raw) |
| - if err != nil || again != start { |
| + if err != nil { |
| return "", os.ErrPermission |
| } |
| + if again != start { |
| + return "", errGenerationTaskReplaced |
| + } |
| return start, nil |
| } |
| func (k generationKernel) absent(ctx context.Context, r release.GenerationReservation) (string, error) { |
| @@ -471,7 +477,7 @@ func (k generationKernel) absent(ctx context.Context, r release.GenerationReserv |
| } |
| tasks, err := generationNames(filepath.Join(k.proc, name, "task")) |
| if err != nil { |
| - return "", err |
| + return "", &generationTaskRefusal{task: filepath.Join(k.proc, name), err: err} |
| } |
| if len(tasks) == 0 { |
| return "", os.ErrPermission |
| @@ -486,7 +492,7 @@ func (k generationKernel) absent(ctx context.Context, r release.GenerationReserv |
| } |
| start, err := k.task(ctx, filepath.Join(k.proc, name, "task", task), r.Binding, ns, refs) |
| if err != nil { |
| - return "", fmt.Errorf("%s: %w", filepath.Join(k.proc, name, "task", task), err) |
| + return "", &generationTaskRefusal{task: filepath.Join(k.proc, name, "task", task), err: err} |
| } |
| observations[name+"/"+task] = start |
| } |
diff --git a/internal/host/rootgeneration_services_linux.go b/internal/host/rootgeneration_services_linux.go| index c29da9545..a75d7b92f 100644 |
| --- a/internal/host/rootgeneration_services_linux.go |
| +++ b/internal/host/rootgeneration_services_linux.go |
| @@ -4,10 +4,15 @@ package host |
| import ( |
| "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| "fmt" |
| + "io" |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "slices" |
| "strconv" |
| "strings" |
| @@ -16,23 +21,120 @@ import ( |
| ) |
| type generationService struct { |
| - group, executable string |
| - main int |
| - selected rootstate.FileIdentity |
| + group, executable, selectedPath string |
| + main int |
| + selected rootstate.FileIdentity |
| } |
| +// generationServiceEnv is what the service lookup reads besides the task's |
| +// own /proc entries: systemd's view of the unit (show), the unit files' |
| +// ownership (trust), the main process's cgroup (under proc), and, for a |
| +// task still running a renamed-over binary, the box's signed router images |
| +// (binary, under opt) and the owner every trusted file must have. The |
| +// production values are generationServiceReader's; tests replace the parts |
| +// a non-root test cannot provide. |
| +type generationServiceEnv struct { |
| + proc, opt string |
| + owner uint32 |
| + show func(ctx context.Context, unit string) (map[string]string, error) |
| + trust func(path string) error |
| + binary func(opt, path string) (rootFloorBinary, error) |
| +} |
| + |
| +// generationServiceRefusal is a refusal of the service lookup. It names the |
| +// check, the unit, the task's cgroup and its exe link, so that refusals |
| +// that used to read as a bare "permission denied" can be told apart, and |
| +// it wraps the cause, so errors.Is still sees os.ErrPermission or a task |
| +// that exited. |
| +type generationServiceRefusal struct { |
| + check, unit, group, exe string |
| + err error |
| +} |
| + |
| +func (r *generationServiceRefusal) Error() string { |
| + return fmt.Sprintf("%s check refused: unit %s, cgroup %s, exe %s: %v", r.check, r.unit, r.group, r.exe, r.err) |
| +} |
| + |
| +func (r *generationServiceRefusal) Unwrap() error { return r.err } |
| + |
| func generationServiceReader(ctx context.Context) func(string, []byte) (bool, error) { |
| + return generationServiceEnv{proc: "/proc", opt: "/opt/carlos", show: generationServiceShow, trust: generationServiceTrust, binary: readRootFloorBinary}.reader(ctx) |
| +} |
| + |
| +func generationServiceShow(ctx context.Context, unit string) (map[string]string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", "show", unit, "-p", "ControlGroup", "-p", "MainPID", "-p", "ExecStart", "-p", "FragmentPath", "-p", "DropInPaths").Output() |
| + if err != nil { |
| + return nil, err |
| + } |
| + props := map[string]string{} |
| + for _, line := range strings.Split(string(out), "\n") { |
| + if k, v, ok := strings.Cut(line, "="); ok { |
| + props[k] = v |
| + } |
| + } |
| + return props, nil |
| +} |
| + |
| +func generationServiceTrust(file string) error { |
| + file, err := filepath.EvalSymlinks(file) |
| + if err != nil { |
| + return err |
| + } |
| + f, err := rootstate.OpenTrustedFile(file) |
| + if err != nil { |
| + return err |
| + } |
| + f.Close() |
| + return nil |
| +} |
| + |
| +func (env generationServiceEnv) reader(ctx context.Context) func(string, []byte) (bool, error) { |
| units := map[string]generationService{} |
| + var proven []string |
| + var provenErr error |
| + proved := false |
| + // The digests of the current and the previous router binary, each |
| + // proven against a signed identity the box holds, read once per census |
| + // pass and only if a task's exe has been deleted. |
| + prove := func() ([]string, error) { |
| + if !proved { |
| + proved = true |
| + var errs []error |
| + for _, name := range []string{"carlos", "carlos.prev"} { |
| + b, err := env.binary(env.opt, filepath.Join(env.opt, name)) |
| + if err != nil { |
| + if name == "carlos" || !errors.Is(err, os.ErrNotExist) { |
| + errs = append(errs, fmt.Errorf("%s: %w", name, err)) |
| + } |
| + continue |
| + } |
| + proven = append(proven, b.Digest) |
| + } |
| + if len(proven) == 0 { |
| + provenErr = errors.Join(append(errs, os.ErrPermission)...) |
| + } |
| + } |
| + return proven, provenErr |
| + } |
| return func(path string, status []byte) (bool, error) { |
| + name, nameErr := os.Readlink(path + "/exe") |
| + exe := name |
| + if nameErr != nil { |
| + exe = "unreadable" |
| + } |
| + unit, group := "unknown", "unknown" |
| + refuse := func(check string, err error) error { |
| + return &generationServiceRefusal{check: check, unit: unit, group: group, exe: exe, err: err} |
| + } |
| raw, err := generationRead(path + "/cgroup") |
| if err != nil { |
| - return false, err |
| + return false, refuse("cgroup", err) |
| } |
| - group := strings.TrimPrefix(strings.TrimSpace(string(raw)), "0::") |
| + group = strings.TrimPrefix(strings.TrimSpace(string(raw)), "0::") |
| if !strings.HasPrefix(group, "/") || strings.Contains(group, "\n") || strings.Contains(group, "/carlos-instances.slice/") { |
| - return false, os.ErrPermission |
| + return false, refuse("cgroup", os.ErrPermission) |
| } |
| - unit := filepath.Base(group) |
| + unit = filepath.Base(group) |
| for _, part := range strings.Split(group, "/") { |
| if strings.HasSuffix(part, ".service") { |
| unit = part |
| @@ -40,93 +142,137 @@ func generationServiceReader(ctx context.Context) func(string, []byte) (bool, er |
| } |
| } |
| if !strings.HasSuffix(unit, ".service") && group != "/init.scope" { |
| - return false, os.ErrPermission |
| + return false, refuse("unit", os.ErrPermission) |
| } |
| s, ok := units[unit] |
| if !ok { |
| if group == "/init.scope" { |
| s = generationService{group: group, main: 1} |
| } else { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", unit, "-p", "ControlGroup", "-p", "MainPID", "-p", "ExecStart", "-p", "FragmentPath", "-p", "DropInPaths").Output() |
| + props, err := env.show(ctx, unit) |
| if err != nil { |
| - return false, err |
| - } |
| - props := map[string]string{} |
| - for _, line := range strings.Split(string(out), "\n") { |
| - if k, v, ok := strings.Cut(line, "="); ok { |
| - props[k] = v |
| - } |
| + return false, refuse("systemctl show", err) |
| } |
| s.group, s.main = props["ControlGroup"], 0 |
| s.main, err = strconv.Atoi(props["MainPID"]) |
| if err != nil || s.main <= 0 || props["FragmentPath"] == "" { |
| - return false, os.ErrPermission |
| + return false, refuse("main pid", os.ErrPermission) |
| } |
| for _, file := range append([]string{props["FragmentPath"]}, strings.Fields(props["DropInPaths"])...) { |
| - file, err = filepath.EvalSymlinks(file) |
| - if err != nil { |
| - return false, err |
| - } |
| - f, err := rootstate.OpenTrustedFile(file) |
| - if err != nil { |
| - return false, err |
| + if err := env.trust(file); err != nil { |
| + return false, refuse("unit file "+file, err) |
| } |
| - f.Close() |
| } |
| _, tail, found := strings.Cut(props["ExecStart"], "path=") |
| if !found { |
| - return false, os.ErrPermission |
| + return false, refuse("exec start", os.ErrPermission) |
| } |
| s.executable, _, _ = strings.Cut(tail, " ;") |
| if unit == "carlos-edge.service" && s.executable == "/opt/carlos/system/guard/carlos" { |
| if !generationGuardEdgeStart(unit, props["ExecStart"]) { |
| - return false, os.ErrPermission |
| + return false, refuse("guard start", os.ErrPermission) |
| } |
| - if _, err := readRootFloorBinary("/opt/carlos", s.executable); err != nil { |
| - return false, err |
| + if _, err := env.binary(env.opt, s.executable); err != nil { |
| + return false, refuse("guard binary", err) |
| } |
| - selected, err := readRootFloorBinary("/opt/carlos", "/opt/carlos/carlos") |
| + selected, err := env.binary(env.opt, filepath.Join(env.opt, "carlos")) |
| if err != nil { |
| - return false, err |
| + return false, refuse("selected binary", err) |
| } |
| - s.selected = selected.File |
| + s.selected, s.selectedPath = selected.File, filepath.Join(env.opt, "carlos") |
| } |
| } |
| units[unit] = s |
| } |
| supervisor := generationServiceSupervisor(unit, group, s.group, status, s.main) |
| if !generationServiceGroup(group, s.group) && !supervisor { |
| - return false, os.ErrPermission |
| - } |
| - name, err := os.Readlink(path + "/exe") |
| - if err != nil { |
| - return false, err |
| + return false, refuse("group", os.ErrPermission) |
| } |
| - actual, err := generationServiceExecutable(path, name) |
| - if err != nil { |
| - return false, fmt.Errorf("%s: %w", name, err) |
| + if nameErr != nil { |
| + return false, refuse("exe link", nameErr) |
| } |
| // Non-root services may execute only the program selected by their |
| // root-owned unit. UID and a service-looking cgroup are insufficient. |
| - if _, err := generationRootTask(status); err != nil || s.selected != (rootstate.FileIdentity{}) { |
| - want, e := generationIdentity(s.executable) |
| + _, rootErr := generationRootTask(status) |
| + checked := rootErr != nil || s.selected != (rootstate.FileIdentity{}) |
| + if program, deleted := strings.CutSuffix(name, " (deleted)"); deleted && checked { |
| + want := s.executable |
| if s.selected != (rootstate.FileIdentity{}) { |
| - want, e = s.selected, nil |
| + want = s.selectedPath |
| } |
| - if e != nil || want != actual { |
| - return false, os.ErrPermission |
| + if err := env.deletedProgram(path, program, want, prove); err != nil { |
| + return false, refuse("deleted exe", err) |
| + } |
| + } else { |
| + actual, err := generationServiceExecutable(path, name) |
| + if err != nil { |
| + return false, refuse("exe", fmt.Errorf("%s: %w", name, err)) |
| + } |
| + if checked { |
| + want, e := generationIdentity(s.executable) |
| + if s.selected != (rootstate.FileIdentity{}) { |
| + want, e = s.selected, nil |
| + } |
| + if e != nil || want != actual { |
| + return false, refuse("selected program", os.ErrPermission) |
| + } |
| } |
| } |
| - mainGroup, err := generationRead("/proc/" + strconv.Itoa(s.main) + "/cgroup") |
| + mainGroup, err := generationRead(env.proc + "/" + strconv.Itoa(s.main) + "/cgroup") |
| mainPath := strings.TrimPrefix(strings.TrimSpace(string(mainGroup)), "0::") |
| if err != nil || (!generationServiceGroup(mainPath, s.group) && !(supervisor && mainPath == group)) { |
| - return false, os.ErrPermission |
| + if err == nil { |
| + err = os.ErrPermission |
| + } |
| + return false, refuse("main cgroup", err) |
| } |
| return true, nil |
| } |
| } |
| +// deletedProgram accepts a non-root service task still running a carlos |
| +// binary that an apply has since renamed over, whose exe link reads |
| +// "<program> (deleted)". The program must be the one the unit selects and |
| +// the box's router binary, <opt>/carlos. The task's own image, opened |
| +// through /proc/<pid>/exe, must be a root-owned regular file with no links |
| +// left that no group or other can write. Its bytes must hash to the router |
| +// artifact of the signed identity of the current or the previous binary |
| +// (<opt>/carlos, <opt>/carlos.prev), proven by readRootFloorBinary, the |
| +// proof the guard makes before it execs one. Anything else refuses, and |
| +// the census's reference checks still run on an accepted task. |
| +func (env generationServiceEnv) deletedProgram(task, program, want string, prove func() ([]string, error)) error { |
| + if program != want || want != filepath.Join(env.opt, "carlos") { |
| + return fmt.Errorf("%s is not this unit's router binary: %w", program, os.ErrPermission) |
| + } |
| + f, err := os.Open(task + "/exe") |
| + if err != nil { |
| + return err |
| + } |
| + defer f.Close() |
| + var st unix.Stat_t |
| + if err := unix.Fstat(int(f.Fd()), &st); err != nil { |
| + return err |
| + } |
| + if st.Uid != env.owner || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0022 != 0 || st.Nlink != 0 || st.Size > 512<<20 { |
| + return fmt.Errorf("image is not an unlinked root-owned file: %w", os.ErrPermission) |
| + } |
| + sum := sha256.New() |
| + if n, err := io.Copy(sum, io.LimitReader(f, 512<<20+1)); err != nil { |
| + return err |
| + } else if n > 512<<20 { |
| + return os.ErrPermission |
| + } |
| + digests, err := prove() |
| + if err != nil { |
| + return err |
| + } |
| + if !slices.Contains(digests, hex.EncodeToString(sum.Sum(nil))) { |
| + return fmt.Errorf("image is neither the current nor the previous signed router build: %w", os.ErrPermission) |
| + } |
| + return nil |
| +} |
| + |
| func generationGuardEdgeStart(unit, start string) bool { |
| if unit != "carlos-edge.service" || strings.Count(start, "{") != 1 || strings.Count(start, "}") != 1 { |
| return false |
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go| index 8cbcf2a2c..62d6d8eef 100644 |
| --- a/internal/host/systemapply.go |
| +++ b/internal/host/systemapply.go |
| @@ -328,9 +328,15 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) { |
| return err |
| } |
| } |
| - // Rejected floor recovery must retain staging and the journal. |
| + // Rejected floor recovery must retain staging and the journal. A |
| + // settlement deferred with no journal open (errSettlementDeferred) lets |
| + // --recover go on and exit 0; it is not tried again at the end. |
| + deferred := false |
| if err := a.checkGuardRecovery(ctx); err != nil { |
| - return err |
| + if !a.deferSettlement(recover, err) { |
| + return err |
| + } |
| + deferred = true |
| } |
| defer func() { |
| active, err := a.activeFloor() |
| @@ -339,13 +345,17 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) { |
| return |
| } |
| if !active { |
| - a.settleUpdateBegun(ctx) |
| + if !deferred { |
| + a.settleUpdateBegun(ctx) |
| + } |
| _ = os.RemoveAll(a.stagingDir()) |
| return |
| } |
| - if j, e := readSystemJournal(a.optDir); e == nil && j == nil { |
| + if j, e := readSystemJournal(a.optDir); e == nil && j == nil && !deferred { |
| if err := a.checkGuardRecovery(ctx); err != nil { |
| - retErr = errors.Join(retErr, err) |
| + if !a.deferSettlement(recover, err) { |
| + retErr = errors.Join(retErr, err) |
| + } |
| return |
| } |
| a.settleUpdateBegun(ctx) |
diff --git a/internal/host/systemparticipation.go b/internal/host/systemparticipation.go| index 268a66731..120738853 100644 |
| --- a/internal/host/systemparticipation.go |
| +++ b/internal/host/systemparticipation.go |
| @@ -224,7 +224,11 @@ func (a *systemApplier) checkUnarmedParticipationRecovery(ctx context.Context) e |
| return err |
| } |
| if recover { |
| - if err := a.controllersRecovered(ctx); err != nil { |
| + settle := a.controllersRecovered |
| + if j == nil { |
| + settle = a.settleWithoutJournal |
| + } |
| + if err := settle(ctx); err != nil { |
| return err |
| } |
| } |