From 60eccb3706a3752de15bac50451c5cb06c207259 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Proulx?= <76956526+fproulx-boostsecurity@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:02:13 -0400 Subject: [PATCH 1/3] feat: add reversible emergency trust repair for macOS and Linux --- README.md | 111 ++- cmd/embarass/batch.go | 11 +- cmd/embarass/batch_terminal.go | 33 +- cmd/embarass/fix.go | 297 ++++++++ cmd/embarass/fix_terminal.go | 350 +++++++++ cmd/embarass/fix_test.go | 150 ++++ cmd/embarass/root.go | 30 +- cmd/embarass/terminal.go | 21 +- docs/research/linux-emergency-fix.md | 96 +++ docs/research/macos-emergency-fix.md | 91 +++ go.mod | 2 +- pkg/repair/bundle.go | 170 +++++ pkg/repair/bundle_test.go | 108 +++ pkg/repair/files_other.go | 19 + pkg/repair/files_unix.go | 72 ++ pkg/repair/linux.go | 696 ++++++++++++++++++ pkg/repair/linux_test.go | 245 ++++++ pkg/repair/store.go | 301 ++++++++ pkg/repair/store_test.go | 186 +++++ pkg/repair/testdata/README.md | 23 + pkg/repair/testdata/aaa.pem | 25 + pkg/repair/testdata/emsign.pem | 15 + .../testdata/legacy-negative-serial.pem | 31 + pkg/repair/testdata/native-smoke.sh | 99 +++ pkg/runner/completion_test.go | 59 ++ pkg/runner/runner.go | 42 +- 26 files changed, 3259 insertions(+), 24 deletions(-) create mode 100644 cmd/embarass/fix.go create mode 100644 cmd/embarass/fix_terminal.go create mode 100644 cmd/embarass/fix_test.go create mode 100644 docs/research/linux-emergency-fix.md create mode 100644 docs/research/macos-emergency-fix.md create mode 100644 pkg/repair/bundle.go create mode 100644 pkg/repair/bundle_test.go create mode 100644 pkg/repair/files_other.go create mode 100644 pkg/repair/files_unix.go create mode 100644 pkg/repair/linux.go create mode 100644 pkg/repair/linux_test.go create mode 100644 pkg/repair/store.go create mode 100644 pkg/repair/store_test.go create mode 100644 pkg/repair/testdata/README.md create mode 100644 pkg/repair/testdata/aaa.pem create mode 100644 pkg/repair/testdata/emsign.pem create mode 100644 pkg/repair/testdata/legacy-negative-serial.pem create mode 100644 pkg/repair/testdata/native-smoke.sh create mode 100644 pkg/runner/completion_test.go diff --git a/README.md b/README.md index a1e6220..3833300 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,10 @@ `emBarrass` is a local, open-source validator for the weak eMudhra intermediate CA keys disclosed in October 2026. It wraps a command, presents that command with a forged TLS certificate signed by a recovered eMudhra key, and reports whether the command accepted it. -It does **not** replace the command's CA bundle, disable certificate verification, modify the host trust store, or forward traffic to the destination. +The command wrapper and `batch` do **not** replace the command's CA bundle, +disable certificate verification, modify the host trust store, or forward +traffic to the destination. The explicit `fix` subcommand can apply the +reversible macOS and Linux emergency mitigations described below. ## Quickstart @@ -32,6 +35,19 @@ embarass `make install` installs the current checkout into `GOBIN`, or `GOPATH/bin` when `GOBIN` is unset. +**Completely or partially embarrassed? Take back trust:** + +```console +embarass fix --dry-run +embarass fix +embarass batch +``` + +`fix` previews and applies an emergency repair to supported macOS/Linux system +stores, with confirmation and recovery data. Private CA bundles and containers +need separate updates. See [emergency repair](#emergency-repair-on-macos-and-linux) +for platform coverage and undo. + Alternatively, install directly with Go: ```console @@ -144,6 +160,99 @@ The default output is an interactive, human-readable terminal report with distin Running `embarass` without a child command prints a short set of copyable examples. `embarass --help` includes the complete list above. +### Emergency repair on macOS and Linux + +```console +embarass fix --dry-run +embarass fix +embarass fix --yes --headless +embarass fix --undo +``` + +`fix` detects a supported system store and displays a colored repair plan with +the exact certificate fingerprints. It asks for confirmation and records recovery +data before removing trust in `AAA Certificate Services` and +`emSign ECC Root CA - G3`. It follows the +[incident advisory's platform workarounds](https://emudhra.we-have-a-problem.com/#workarounds). +**Legitimate chains relying solely on either root also lose trust.** + +| Platform | Emergency repair | +|---|---| +| macOS | Atomically remove fingerprint-matched PEM blocks from `/etc/ssl/cert.pem`. | +| Debian, Ubuntu, Alpine | Deselect fingerprint-matched vendor source entries in `/etc/ca-certificates.conf`, then run `/usr/sbin/update-ca-certificates`. | +| Fedora, RHEL, CentOS, Rocky, AlmaLinux, Amazon Linux, Oracle Linux | Add individually recorded distrust files under `/etc/pki/ca-trust/source/blocklist` (or the legacy `blacklist` directory), then run `/usr/bin/update-ca-trust extract`. | + +On Linux, vendor CA-package updates remain the preferred fix. This emergency +repair uses already installed certificates and native tools; it does not run a +package manager or download certificates. Minimal Alpine images with only +`ca-certificates-bundle` need the full `ca-certificates` package first. Other +Linux distributions are reported as unsupported rather than guessing their +store layout. See the [Linux source review](docs/research/linux-emergency-fix.md). + +Native repair, both forged trust paths, unrelated enterprise trust, and undo +have been exercised in disposable Debian, Alpine, and Fedora containers. +The other listed distributions share those implementations but have not each +been tested in a container. Arch and openSUSE are not yet supported. + +Run it as your normal user. Only the file transaction requests `sudo`; before +and after probes run without elevation. The animated terminal shows actual +operation progress and a final receipt with the backup location and undo +command. `--dry-run` only inspects the file; it neither writes nor runs probes. +Noninteractive application requires `--yes`. `--headless` prints plain progress. + +On macOS, the repair targets `/etc/ssl/cert.pem` (its canonical path is +`/private/etc/ssl/cert.pem`). Every certificate is parsed, and removal uses +pinned SHA-256 certificate fingerprints. Unrelated certificates and descriptive +text are preserved. A protected adjacent receipt and original bundle are +retained; symlinks, unsafe ownership, concurrent emBarrass writers, and changed +preview contents are refused. Undo refuses an intervening OS or administrator +edit and retains the original backup in an archived receipt directory. +Undo reintroduces the original trust anchors. If a transaction is interrupted, +inspect `embarass fix --undo --dry-run` before recovering it. + +The macOS repair does not lock the bundle against changes, disable Apple updates, or +install a background process that reapplies it. Apple can replace the file +normally. A later replacement becomes the active bundle; undo refuses to +overwrite contents that differ from the recorded repair. This does not predict +what a future Apple update will contain, so recheck afterward. + +On Linux, the preview names the configuration/distrust location and native +regeneration command. Regeneration runs the distribution's installed hooks and +can update several outputs; it is **not an atomic bundle swap**. Verification +checks that the regenerated TLS bundle lacks the targeted roots and retains +unrelated certificates. An updater failure leaves the receipt at +`/etc/embarass-fix/receipt.json` for inspection and recovery. Existing local CA +copies that bypass Debian-style deselection require manual review. + +Linux undo reverses only recorded source changes and regenerates from the +**current vendor policy**. It never copies an old generated bundle over a vendor +update. Modified Debian/Ubuntu/Alpine configuration or vendor source certificates +cause undo to refuse; pre-existing p11-kit distrust files remain untouched. +Native Java and other trust outputs depend on installed hooks and need their own +client checks. The TLS-bundle result is not a blanket assertion about those stores. + +Verification challenges the system `/usr/bin/curl` against both local DV-G3B +forgeries, explicitly selecting this bundle and an empty additional CA +directory. Curl startup configuration is disabled. A rejected result requires +a certificate-verification exit code as well as the local TLS observation. +No external test server or certificate download is needed. A successful bundle +edit and a successful behavioral check are reported separately; an +inconclusive probe is never labeled protected. Running the entire command as +root skips behavioral probes and reports verification incomplete. + +These repairs cover the **selected system store only**. Apple pip, independent +runtime bundles, and containers may remain exposed. Use `embarass batch` as +your normal user to inspect them; its intentionally historical `docker/git` +fixture is not a host-repair success criterion. Vendor updates can replace +the system bundle or its inputs, so check again after updates. Each container +must be repaired or rebuilt separately. See the +[platform research](docs/research/macos-emergency-fix.md). + +Repair exit codes: `0` means both post-repair probes rejected the forgeries +(or a preview/undo completed); `1` means a post-repair probe still accepted a +forgery; `2` means an error, cancellation, or incomplete verification. A repair +can remain applied when verification exits `1` or `2`; consult the receipt. + ### Batch testing installed tools `embarass batch` discovers `curl`, `git`, `gh`, `wget`, `npm`, `go`, diff --git a/cmd/embarass/batch.go b/cmd/embarass/batch.go index 0eeb436..16e7af5 100644 --- a/cmd/embarass/batch.go +++ b/cmd/embarass/batch.go @@ -33,7 +33,12 @@ deleted temporary workspace. The docker/git probe may pull and retain one immutable, digest-pinned image.`, Example: fmt.Sprintf(` %[1]s batch %[1]s batch --chain emsign - %[1]s batch --yes --headless`, invocation), + %[1]s batch --yes --headless + + # Completely or partially embarrassed? Preview, repair, and recheck + %[1]s fix --dry-run + %[1]s fix + %[1]s batch`, invocation), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return app.runBatch(cmd) @@ -109,6 +114,7 @@ func (app *application) runBatchTerminal( app.timeout, app.batchYes, ) + model.invocation = app.displayedInvocation() program := tea.NewProgram( model, tea.WithInput(cmd.InOrStdin()), @@ -158,6 +164,9 @@ func (app *application) runBatchHeadless( Int("errors", summary.failed). Int("unavailable", summary.skipped). Msg("BATCH COMPLETE") + if summary.vulnerable > 0 { + app.logRepairCallToAction(log) + } return summary } diff --git a/cmd/embarass/batch_terminal.go b/cmd/embarass/batch_terminal.go index 719bb9a..49d691f 100644 --- a/cmd/embarass/batch_terminal.go +++ b/cmd/embarass/batch_terminal.go @@ -40,20 +40,21 @@ type batchItem struct { } type batchModel struct { - ctx context.Context - cancel context.CancelFunc - styles terminalStyles - plan batchtest.Plan - run runFunc - timeout time.Duration - items []batchItem - current int - spinner int - width int - autoStart bool - confirmed bool - done bool - canceled bool + ctx context.Context + cancel context.CancelFunc + styles terminalStyles + plan batchtest.Plan + run runFunc + timeout time.Duration + invocation string + items []batchItem + current int + spinner int + width int + autoStart bool + confirmed bool + done bool + canceled bool } type batchStartMsg struct{} @@ -207,6 +208,7 @@ func (model batchModel) View() string { "", " " + model.styles.cyanBold.Render("BATCH TRUST PREFLIGHT"), " " + model.styles.muted.Render("intercepted traffic stays local · temporary caches removed"), + " " + model.styles.cyanBold.Render("EXPOSED?") + " Preview emergency repair: " + displayedInvocation(model.invocation) + " fix --dry-run", "", } if model.mayPullImage() { @@ -268,6 +270,9 @@ func (model batchModel) View() string { " "+model.styles.muted.Render("q cancels the active child and remaining probes"), ) } + if (model.done || model.canceled) && model.summary().vulnerable > 0 { + lines = append(lines, "", repairCallToAction(model.styles, model.invocation, model.width-4)) + } return strings.Join(lines, "\n") } diff --git a/cmd/embarass/fix.go b/cmd/embarass/fix.go new file mode 100644 index 0000000..fce2e8c --- /dev/null +++ b/cmd/embarass/fix.go @@ -0,0 +1,297 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "bytes" + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "time" + + "github.com/boostsecurityio/emBarrass/pkg/certforge" + "github.com/boostsecurityio/emBarrass/pkg/repair" + "github.com/boostsecurityio/emBarrass/pkg/runner" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" + "github.com/spf13/cobra" +) + +type fixOptions struct{ dryRun, yes, undo bool } + +func newFixCommand(app *application) *cobra.Command { + var options fixOptions + command := &cobra.Command{ + Use: "fix", Short: "Apply a reversible emergency repair to supported system CA stores", + Long: `Preview and back up a platform-specific emergency trust repair, then +challenge both eMudhra trust paths with system curl. Legitimate chains relying +solely on the affected roots will also lose trust. + +macOS: remove exact root certificates from /etc/ssl/cert.pem. +Debian, Ubuntu, Alpine: deselect roots and run update-ca-certificates. +Fedora/RHEL family: add local distrust files and run update-ca-trust extract. +Linux regeneration runs installed distro hooks and may update multiple stores; +undo reverses our policy changes and rebuilds from current vendor sources. + +Prefer vendor CA-package updates when available. Independent application +bundles, Apple pip, and containers need separate checks. Use batch for those. + +Run as your normal user; only the file transaction requests sudo. Undo refuses +to overwrite later OS or administrator changes. No certificate is downloaded.`, + Example: fmt.Sprintf(" %[1]s fix --dry-run\n %[1]s fix\n %[1]s fix --yes --headless\n %[1]s fix --undo", app.displayedInvocation()), + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { return app.runFix(cmd, options) }, + } + command.Flags().BoolVar(&options.dryRun, "dry-run", false, "preview the repair without writing or running probes") + command.Flags().BoolVarP(&options.yes, "yes", "y", false, "apply the displayed repair without prompting") + command.Flags().BoolVar(&options.undo, "undo", false, "reverse the recorded repair; trust may be reintroduced") + command.Flags().BoolVar(&app.headless, "headless", false, "emit plain repair progress without animation") + command.Flags().BoolVarP(&app.verbose, "verbose", "v", false, "enable debug logging") + return command +} + +// The privileged subprocess has a fixed target, no discovery/probes, and an +// expected input hash. Its caller cannot choose a file or provide replacement bytes. +func newFixCommitCommand() *cobra.Command { + var undo bool + command := &cobra.Command{Use: "_fix-commit expected-sha256", Hidden: true, Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if os.Geteuid() != 0 { + return errors.New("repair transaction requires administrator access") + } + decoded, err := hex.DecodeString(args[0]) + if err != nil || len(decoded) != 32 { + return errors.New("invalid expected bundle hash") + } + store, err := repair.System() + if err != nil { + return fmt.Errorf("open system repair: %w", err) + } + receipt, err := store.Apply(args[0], undo) + if err != nil { + return fmt.Errorf("commit system repair: %w", err) + } + if err := json.NewEncoder(cmd.OutOrStdout()).Encode(receipt); err != nil { + return fmt.Errorf("write repair receipt: %w", err) + } + return nil + }, + } + command.Flags().BoolVar(&undo, "undo", false, "restore recorded bundle") + return command +} + +func (app *application) runFix(cmd *cobra.Command, options fixOptions) error { + store, err := repair.System() + if err != nil { + return fmt.Errorf("open system repair: %w", err) + } + plan, err := store.Inspect() + if options.undo { + plan, err = store.UndoPlan() + } + if err != nil { + return fmt.Errorf("inspect repair plan: %w", err) + } + ui := newTerminalUI(cmd.ErrOrStderr()) + if app.headless { + renderer := lipgloss.NewRenderer(cmd.ErrOrStderr()) + renderer.SetColorProfile(termenv.Ascii) + ui.styles = newTerminalStyles(renderer) + } + interactive := ui.interactive && !app.headless + preview := newFixModel(ui.styles, plan, options.undo, app.displayedInvocation()) + preview.dryRun = options.dryRun + changes := options.undo || len(plan.Removed) > 0 + app.terminalStarted = true + if options.dryRun || options.yes || !changes { + preview.confirmed = options.yes || !changes + if _, err := fmt.Fprintln(cmd.ErrOrStderr(), preview.View()); err != nil { + return fmt.Errorf("write repair preview: %w", err) + } + } else { + if !interactive { + return errors.New("repair confirmation requires a terminal; use --dry-run to inspect or --yes to apply") + } + program := tea.NewProgram(preview, tea.WithInput(cmd.InOrStdin()), tea.WithOutput(cmd.ErrOrStderr())) + final, err := program.Run() + if err != nil { + return fmt.Errorf("run repair preview: %w", err) + } + preview = final.(fixModel) + if !preview.confirmed { + app.exitCode = exitInconclusive + return nil + } + } + if options.dryRun { + return nil + } + var commit func() (repair.Receipt, error) + if changes { + if os.Geteuid() == 0 { + commit = func() (repair.Receipt, error) { return store.Apply(plan.BeforeSHA256, options.undo) } + } else { + // Leave raw terminal mode before sudo needs a password. The subsequent + // transaction is noninteractive, so prompts never collide with animation. + if _, err := fmt.Fprintln(cmd.ErrOrStderr(), "\n Administrator access is needed for the bundle transaction."); err != nil { + return fmt.Errorf("write privilege notice: %w", err) + } + auth := exec.CommandContext(cmd.Context(), "/usr/bin/sudo", "-v") + auth.Stdin, auth.Stdout, auth.Stderr = cmd.InOrStdin(), cmd.ErrOrStderr(), cmd.ErrOrStderr() + if err := auth.Run(); err != nil { + return fmt.Errorf("authorize repair; bundle unchanged: %w", err) + } + executable, err := os.Executable() + if err != nil { + return fmt.Errorf("locate repair executable: %w", err) + } + commit = func() (repair.Receipt, error) { return commitWithSudo(executable, plan.BeforeSHA256, options.undo) } + } + } + temp, err := os.MkdirTemp("", "embarass-fix-probe-*") + if err != nil { + return fmt.Errorf("create isolated probe directory: %w", err) + } + defer func() { _ = os.Remove(temp) }() + ctx, cancel := context.WithCancel(cmd.Context()) + defer cancel() + model := newFixModel(ui.styles, plan, options.undo, app.displayedInvocation()) + model.confirmed, model.running = true, true + model.cancel = cancel + model.steps = app.fixSteps(ctx, plan, temp, commit, options.undo) + if interactive { + program := tea.NewProgram(model, tea.WithInput(cmd.InOrStdin()), tea.WithOutput(cmd.ErrOrStderr())) + final, err := program.Run() + if err != nil { + return fmt.Errorf("run repair display; inspect bundle and recovery record before retrying: %w", err) + } + model = final.(fixModel) + } else { + for i := range model.steps { + result := model.steps[i].run() + model.record(i, result) + if _, err := fmt.Fprintf(cmd.ErrOrStderr(), " %s: %s\n", model.steps[i].label, result.detail); err != nil { + return fmt.Errorf("write repair progress: %w", err) + } + if model.failed { + break + } + } + model.done = true + if _, err := fmt.Fprintln(cmd.ErrOrStderr(), model.View()); err != nil { + return fmt.Errorf("write repair result: %w", err) + } + } + app.exitCode = model.exitCode() + return nil +} + +func commitWithSudo(executable, expected string, undo bool) (repair.Receipt, error) { + args := []string{"-n", "--", executable, "_fix-commit", expected} + if undo { + args = append(args, "--undo") + } + // Deliberately not CommandContext: cancellation must not kill a file + // transaction halfway through. The UI waits for its durable receipt. + command := exec.Command("/usr/bin/sudo", args...) + var output, stderr bytes.Buffer + command.Stdout, command.Stderr = &output, &stderr + if err := command.Run(); err != nil { + return repair.Receipt{}, fmt.Errorf("repair transaction: %w: %s", err, oneLine(stderr.String())) + } + var receipt repair.Receipt + if err := json.Unmarshal(output.Bytes(), &receipt); err != nil { + return receipt, fmt.Errorf("read transaction receipt; inspect bundle before retrying: %w", err) + } + return receipt, nil +} + +func (app *application) fixSteps(ctx context.Context, plan repair.Plan, emptyCAPath string, commit func() (repair.Receipt, error), undo bool) []fixStep { + steps := make([]fixStep, 0, 5) + bundle := plan.BundlePath + if bundle == "" { + bundle = repair.BundlePath + } + probe := func(chain certforge.Chain, after bool) fixStep { + prefix := "BEFORE" + if after { + prefix = "AFTER" + } + return fixStep{label: prefix + " / " + chainShortDescription(chain), after: after, run: func() fixStepResult { + if os.Geteuid() == 0 { + return fixStepResult{detail: "NOT TESTED · run as a normal user to verify", outcome: runner.OutcomeInconclusive} + } + result, err := app.run(ctx, runner.Options{ + Command: []string{"/usr/bin/curl", "-q", "--silent", "--output", "/dev/null", "--cacert", bundle, + "--capath", emptyCAPath, "--noproxy", "", "--max-time", "12", "--retry", "0", "https://example.com/"}, + Chain: chain, Timeout: 15 * time.Second, Stdout: io.Discard, Stderr: io.Discard, WorkingDirectory: emptyCAPath, + }) + // A generic TLS failure is not evidence of certificate rejection. + if err != nil || (result.Outcome == runner.OutcomeRejected && result.ChildExitCode != 60) { + return fixStepResult{detail: "NO SIGNAL · certificate decision not confirmed", outcome: runner.OutcomeInconclusive} + } + // Some curl TLS backends verify certificates after completing the + // handshake, then close without an alert. For this fixed HTTPS probe, + // exit 60 plus observed tunnel traffic is explicit peer rejection. + if result.Outcome == runner.OutcomeInconclusive && result.Reason == runner.ReasonNoTLSDecision && result.ChildExitCode == 60 { + return fixStepResult{detail: "REJECTED · curl certificate verification failed", outcome: runner.OutcomeRejected} + } + switch result.Outcome { + case runner.OutcomeVulnerable: + return fixStepResult{detail: "ACCEPTED · forged certificate trusted", outcome: result.Outcome} + case runner.OutcomeRejected: + return fixStepResult{detail: "REJECTED · forged certificate denied", outcome: result.Outcome} + default: + return fixStepResult{detail: "NO SIGNAL · verification inconclusive", outcome: runner.OutcomeInconclusive} + } + }} + } + if !undo && commit != nil { + for _, chain := range allChains { + steps = append(steps, probe(chain, false)) + } + } + if commit != nil { + label := "BACKUP + ATOMIC REPAIR" + if undo { + label = "RESTORE ORIGINAL BUNDLE" + } + if plan.Refresh != "" { + label = "UPDATE NATIVE POLICY + REBUILD" + if undo { + label = "REVERSE LOCAL POLICY + REBUILD" + } + } + steps = append(steps, fixStep{label: label, transaction: true, run: func() fixStepResult { + receipt, err := commit() + if err != nil { + return fixStepResult{detail: err.Error(), err: err, receipt: receipt} + } + detail := fmt.Sprintf("COMMITTED · %d certificate blocks removed", len(plan.Removed)) + if undo { + detail = "RESTORED · original trust anchors reintroduced" + } + if plan.Refresh != "" { + detail = fmt.Sprintf("REGENERATED · %d affected roots distrusted", len(plan.Removed)) + if undo { + detail = "REBUILT · current vendor policy retained" + } + } + return fixStepResult{detail: detail, receipt: receipt} + }}) + } + if !undo { + for _, chain := range allChains { + steps = append(steps, probe(chain, true)) + } + } + return steps +} diff --git a/cmd/embarass/fix_terminal.go b/cmd/embarass/fix_terminal.go new file mode 100644 index 0000000..f0a31e7 --- /dev/null +++ b/cmd/embarass/fix_terminal.go @@ -0,0 +1,350 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/boostsecurityio/emBarrass/pkg/repair" + "github.com/boostsecurityio/emBarrass/pkg/runner" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +type fixStep struct { + label string + after, transaction, finished bool + run func() fixStepResult + result fixStepResult +} + +type fixStepResult struct { + detail string + outcome runner.Outcome + receipt repair.Receipt + err error +} + +type fixTickMsg struct{} +type fixResultMsg struct { + index int + result fixStepResult +} + +type fixModel struct { + styles terminalStyles + plan repair.Plan + invocation string + undo, dryRun, confirmed, running, done, canceled, failed bool + cancelRequested bool + cancel context.CancelFunc + width, frame, current int + steps []fixStep + receipt repair.Receipt +} + +func newFixModel(styles terminalStyles, plan repair.Plan, undo bool, invocation string) fixModel { + if plan.Path == "" { + plan.Path = repair.BundlePath + } + if plan.Platform == "" { + plan.Platform = "macOS system PEM bundle" + } + return fixModel{styles: styles, plan: plan, undo: undo, invocation: invocation, width: 80} +} + +func (model fixModel) Init() tea.Cmd { + if !model.running { + return nil + } + return tea.Batch(model.next(), fixTick()) +} + +func fixTick() tea.Cmd { + return tea.Tick(90*time.Millisecond, func(time.Time) tea.Msg { return fixTickMsg{} }) +} + +func (model fixModel) next() tea.Cmd { + index := model.current + return func() tea.Msg { return fixResultMsg{index, model.steps[index].run()} } +} + +func (model fixModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch message := msg.(type) { + case tea.WindowSizeMsg: + model.width = message.Width + case tea.KeyMsg: + key := strings.ToLower(message.String()) + if !model.running { + if key == "y" { + model.confirmed = true + return model, tea.Quit + } + if key == "n" || key == "q" || key == "esc" || key == "enter" || key == "ctrl+c" { + model.canceled = true + return model, tea.Quit + } + } else if key == "q" || key == "esc" || key == "ctrl+c" { + model.cancelRequested = true + if model.cancel != nil { + model.cancel() + } + // Wait for the current operation, especially an atomic transaction, + // to return its receipt before leaving the UI. + } + case fixTickMsg: + if model.running && !model.done { + model.frame++ + return model, fixTick() + } + case fixResultMsg: + if message.index != model.current || model.done { + return model, nil + } + model.record(message.index, message.result) + model.current++ + if model.cancelRequested || model.failed || model.current == len(model.steps) { + model.canceled = model.cancelRequested + model.done = true + return model, tea.Quit + } + return model, model.next() + } + return model, nil +} + +func (model *fixModel) record(index int, result fixStepResult) { + model.steps[index].finished = true + model.steps[index].result = result + if result.receipt.Backup != "" { + model.receipt = result.receipt + } + if result.err != nil { + model.failed = true + } +} + +func (model fixModel) exitCode() int { + if model.canceled || model.failed || !model.done { + return exitInconclusive + } + if model.undo { + return exitProtected + } + checked, unknown := 0, false + for _, step := range model.steps { + if !step.after { + continue + } + if step.finished && step.result.outcome == runner.OutcomeVulnerable { + return exitVulnerable + } + if !step.finished || step.result.outcome != runner.OutcomeRejected { + unknown = true + } + checked++ + } + if unknown || checked != len(allChains) { + return exitInconclusive + } + return exitProtected +} + +func (model fixModel) View() string { + width := max(24, min(model.width-4, 88)) + inner := width - 4 + wrap := func(text string) string { return lipgloss.NewStyle().Width(inner).Render(text) } + logo := terminalLogo + if width < 64 { + logo = "emBarrass // TRUST REPAIR" + } + logoStyle := model.styles.redBold + if model.done && !model.undo && model.exitCode() == exitProtected { + logoStyle = model.styles.greenBold + } + lines := []string{"", logoStyle.Render(logo), model.styles.muted.Render(centeredTagline(logo)), ""} + title := "EMERGENCY TRUST REPAIR" + if model.undo { + title = "RESTORE ORIGINAL TRUST" + if model.plan.Refresh != "" { + title = "REVERSE LOCAL TRUST OVERRIDE" + } + } + phase := "01 / INSPECT" + if model.running { + phase = "02 / REPAIR + CHALLENGE" + } + if model.done { + phase = "03 / RECEIPT" + } + lines = append(lines, " "+model.styles.cyanBold.Render(title), " "+model.styles.muted.Render(phase), "") + + if !model.running { + body := []string{ + wrap(model.styles.cyanBold.Render("TARGET") + " " + model.plan.Path), + model.styles.muted.Render(model.plan.Platform), "", + } + verb := "REMOVE" + if model.undo { + verb = "RESTORE" + } + if model.plan.Refresh != "" { + verb = "DISTRUST" + if model.undo { + verb = "REVERSE OVERRIDE" + } + } + for _, root := range model.plan.Removed { + body = append(body, wrap(model.styles.redBold.Render("− "+verb)+" "+root.Name), + wrap(model.styles.muted.Render("SHA256 "+root.SHA256)), "") + } + if len(model.plan.Removed) == 0 { + body = append(body, model.styles.cyanBold.Render("TARGET ROOTS ALREADY ABSENT"), "") + } + if model.plan.Refresh != "" { + body = append(body, wrap(model.styles.muted.Render(fmt.Sprintf("%d certificates in the current TLS bundle", model.plan.Certificates))), + wrap(model.styles.cyanBold.Render("REBUILD")+" "+model.plan.Refresh)) + } else if !model.undo { + body = append(body, model.styles.green.Render(fmt.Sprintf("%d other certificates preserved", model.plan.Certificates-len(model.plan.Removed)))) + } else { + body = append(body, model.styles.yellow.Render("Restores the recorded original, including affected roots.")) + } + lines = append(lines, model.box(strings.Join(body, "\n"), width, model.styles.cyan)) + } else { + lines = append(lines, model.progress(width)) + for i, step := range model.steps { + mark, style := "○", model.styles.muted + if step.finished { + mark, style = "✓", model.styles.green + if step.result.err != nil || step.result.outcome == runner.OutcomeVulnerable { + mark, style = "×", model.styles.red + } + if step.result.outcome == runner.OutcomeInconclusive { + mark, style = "?", model.styles.yellow + } + } else if i == model.current && !model.done { + mark, style = batchSpinnerFrames[model.frame%len(batchSpinnerFrames)], model.styles.cyanBold + } + lines = append(lines, " "+style.Render(mark+" "+step.label)) + if step.finished { + lines = append(lines, " "+wrap(style.Render(oneLine(step.result.detail)))) + } + } + } + + lines = append(lines, "") + switch { + case model.done: + title, style := model.verdict() + lines = append(lines, model.box(style.Bold(true).Render(wrap(title)), width, style)) + if model.receipt.Backup != "" { + label := "BACKUP" + if model.plan.Refresh != "" { + label = "RECOVERY RECORD" + } + lines = append(lines, "", " "+model.styles.cyanBold.Render(label), " "+wrap(model.receipt.Backup)) + if !model.undo { + lines = append(lines, " "+model.styles.cyanBold.Render("UNDO")+" "+model.invocation+" fix --undo") + } + } + if !model.undo { + lines = append(lines, "", " "+wrap("Verification scope: system curl with the TLS bundle, both DV-G3B paths.")) + } + lines = append(lines, " "+wrap("Check other tools separately: "+model.invocation+" batch"), + " "+model.styles.muted.Render(fmt.Sprintf("EXIT %d", model.exitCode()))) + case model.canceled: + lines = append(lines, " "+model.styles.yellowBold.Render("CANCELED · bundle unchanged")) + case model.running: + status := "Forged TLS stays local. q stops after the current operation." + if model.cancelRequested { + status = "Stopping… waiting for the current operation's receipt." + } + lines = append(lines, " "+wrap(model.styles.cyan.Render(status))) + default: + warning := "Legitimate chains relying solely on these roots will also lose trust." + if model.undo { + warning = "Undo reintroduces the original trust anchors and may restore exposure." + } + method := "Backup first · atomic replacement · conflict-aware undo" + if model.plan.Refresh != "" { + method = "Native updater + installed hooks · recorded changes · conflict-aware undo" + if model.undo { + warning = "Undo removes our overrides and rebuilds from current vendor policy. Exposure may return." + } + } + lines = append(lines, " "+wrap(model.styles.yellow.Render(warning)), "", + " "+wrap("Tools with private CA bundles and containers need separate checks."), + " "+wrap(model.styles.muted.Render(method)), "") + if model.dryRun { + lines = append(lines, " "+model.styles.cyanBold.Render("DRY RUN · no changes or probes")) + } else if model.confirmed { + lines = append(lines, " "+model.styles.cyanBold.Render("PLAN READY")) + } else { + prompt := "Apply this emergency repair?" + if model.undo { + prompt = "Restore the original trust bundle?" + if model.plan.Refresh != "" { + prompt = "Reverse our local override and rebuild trust?" + } + } + lines = append(lines, " "+wrap(model.styles.bold.Render(prompt)+" "+model.styles.yellowBold.Render("[y/N]")), + " "+model.styles.muted.Render("Only y proceeds. Enter, q, or esc cancels.")) + } + } + return strings.Join(lines, "\n") + "\n" +} + +func (model fixModel) box(body string, width int, style lipgloss.Style) string { + return style.Border(lipgloss.RoundedBorder()).BorderForeground(style.GetForeground()). + Width(width-2).Padding(0, 1).MarginLeft(2).Render(body) +} + +func (model fixModel) progress(width int) string { + completed := 0 + for _, step := range model.steps { + if step.finished { + completed++ + } + } + size := max(10, width-18) + filled := 0 + if len(model.steps) != 0 { + filled = size * completed / len(model.steps) + } + bar := model.styles.cyan.Render(strings.Repeat("━", filled)) + model.styles.muted.Render(strings.Repeat("─", size-filled)) + return fmt.Sprintf(" %s %02d / %02d\n", bar, completed, len(model.steps)) +} + +func (model fixModel) verdict() (string, lipgloss.Style) { + if model.failed { + return "REPAIR INCOMPLETE · REVIEW THE RECEIPT", model.styles.red + } + if model.canceled { + return "STOPPED · REVIEW COMPLETED STEPS", model.styles.yellow + } + if model.undo { + if model.plan.Refresh != "" { + return "LOCAL OVERRIDE REVERSED · STORE REBUILT", model.styles.yellow + } + return "ORIGINAL RESTORED · TRUST REINTRODUCED", model.styles.yellow + } + state := "BUNDLE PATCHED" + if model.plan.Refresh != "" { + state = "NATIVE TRUST REBUILT" + } + if len(model.plan.Removed) == 0 { + state = "TARGET ROOTS ABSENT" + } + switch model.exitCode() { + case exitProtected: + return state + " · BOTH FORGERIES REJECTED", model.styles.green + case exitVulnerable: + return state + " · FORGERY STILL ACCEPTED", model.styles.red + default: + return state + " · VERIFICATION INCOMPLETE", model.styles.yellow + } +} diff --git a/cmd/embarass/fix_test.go b/cmd/embarass/fix_test.go new file mode 100644 index 0000000..87a72b7 --- /dev/null +++ b/cmd/embarass/fix_test.go @@ -0,0 +1,150 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "bytes" + "context" + "errors" + "os" + "testing" + + "github.com/boostsecurityio/emBarrass/pkg/repair" + "github.com/boostsecurityio/emBarrass/pkg/runner" + tea "github.com/charmbracelet/bubbletea" + "github.com/stretchr/testify/require" +) + +func testFixModel() fixModel { + return newFixModel(newTerminalUI(&bytes.Buffer{}).styles, repair.Plan{ + Certificates: 128, + Removed: []repair.Root{{Name: "AAA Certificate Services", SHA256: "d7a7a0fb5d7e2731d771e9484ebcdef71d5f0c3e0a2948782bc83ee0ea699ef4"}, + {Name: "emSign ECC Root CA - G3", SHA256: "86a1ecba089c4a8d3bbe2734c612ba341d813e043cf9e8a862cd5c57a36bbe6b"}}, + }, false, "embarass") +} + +func TestFixPreviewRequiresExplicitConsent(t *testing.T) { + t.Parallel() + for _, key := range []tea.KeyMsg{{Type: tea.KeyEnter}, {Type: tea.KeyEsc}, {Type: tea.KeyCtrlC}, {Type: tea.KeyRunes, Runes: []rune("n")}} { + model := testFixModel() + updated, _ := model.Update(key) + require.False(t, updated.(fixModel).confirmed) + require.True(t, updated.(fixModel).canceled) + } + model := testFixModel() + updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("y")}) + require.True(t, updated.(fixModel).confirmed) + require.Contains(t, model.View(), "Legitimate chains") + require.Contains(t, model.View(), "126 other certificates preserved") +} + +func TestFixCancellationWaitsForTransactionReceipt(t *testing.T) { + t.Parallel() + model := testFixModel() + model.running = true + model.steps = []fixStep{{transaction: true, label: "commit"}, {after: true, label: "verify"}} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + model.cancel = cancel + updated, cmd := model.Update(tea.KeyMsg{Type: tea.KeyCtrlC}) + model = updated.(fixModel) + require.Nil(t, cmd, "must not quit while the transaction is running") + require.False(t, model.done) + require.ErrorIs(t, ctx.Err(), context.Canceled) + updated, cmd = model.Update(fixResultMsg{index: 0, result: fixStepResult{receipt: repair.Receipt{Backup: "/protected/backup.pem"}}}) + model = updated.(fixModel) + require.NotNil(t, cmd) + require.True(t, model.done) + require.True(t, model.canceled) + require.Equal(t, "/protected/backup.pem", model.receipt.Backup) + require.Equal(t, exitInconclusive, model.exitCode()) +} + +func TestFixVerdictRequiresBothAfterChecks(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + results []runner.Outcome + want int + }{ + {"both reject", []runner.Outcome{runner.OutcomeRejected, runner.OutcomeRejected}, exitProtected}, + {"one inconclusive", []runner.Outcome{runner.OutcomeRejected, runner.OutcomeInconclusive}, exitInconclusive}, + {"still exposed", []runner.Outcome{runner.OutcomeVulnerable, runner.OutcomeInconclusive}, exitVulnerable}, + {"one missing", []runner.Outcome{runner.OutcomeRejected}, exitInconclusive}, + } { + t.Run(test.name, func(t *testing.T) { + model := testFixModel() + model.running, model.done = true, true + for _, outcome := range test.results { + model.steps = append(model.steps, fixStep{after: true, finished: true, result: fixStepResult{outcome: outcome}}) + } + require.Equal(t, test.want, model.exitCode()) + if test.want != exitProtected { + require.NotContains(t, model.View(), "BOTH FORGERIES REJECTED") + } + }) + } +} + +func TestFixFailureNeverReportsPatched(t *testing.T) { + t.Parallel() + model := testFixModel() + model.running, model.done = true, true + model.steps = []fixStep{{transaction: true}} + model.record(0, fixStepResult{err: errors.New("disk full"), detail: "disk full"}) + require.Equal(t, exitInconclusive, model.exitCode()) + require.Contains(t, model.View(), "REPAIR INCOMPLETE") + require.NotContains(t, model.View(), "BUNDLE PATCHED") +} + +func TestFixHelpAndCompletionDoNotProbe(t *testing.T) { + t.Parallel() + app := &application{run: func(context.Context, runner.Options) (runner.Result, error) { + t.Fatal("unexpected probe") + return runner.Result{}, nil + }} + command := newRootCommand(app) + var output bytes.Buffer + command.SetOut(&output) + command.SetArgs([]string{"fix", "--help"}) + require.NoError(t, command.Execute()) + require.Contains(t, output.String(), "--dry-run") + require.Contains(t, output.String(), "--undo") + require.Contains(t, executeCompletion(t, "embarass", []string{"__completeNoDesc", "fi"}), "fix") + require.NotContains(t, executeCompletion(t, "embarass", []string{"__completeNoDesc", "_"}), "_fix-commit") +} + +func TestFixVerificationDoesNotConfuseTLSFailureWithCertificateRejection(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root deliberately skips behavioral probes") + } + t.Parallel() + for _, test := range []struct { + name string + result runner.Result + err error + want runner.Outcome + }{ + {"certificate rejected", runner.Result{Outcome: runner.OutcomeRejected, ChildExitCode: 60}, nil, runner.OutcomeRejected}, + {"post-handshake certificate rejection", runner.Result{Outcome: runner.OutcomeInconclusive, Reason: runner.ReasonNoTLSDecision, ChildExitCode: 60}, nil, runner.OutcomeRejected}, + {"unobserved exit 60", runner.Result{Outcome: runner.OutcomeInconclusive, Reason: runner.ReasonNoTraffic, ChildExitCode: 60}, nil, runner.OutcomeInconclusive}, + {"other TLS failure", runner.Result{Outcome: runner.OutcomeRejected, ChildExitCode: 35}, nil, runner.OutcomeInconclusive}, + {"timeout", runner.Result{Outcome: runner.OutcomeInconclusive}, nil, runner.OutcomeInconclusive}, + {"harness failure", runner.Result{}, errors.New("listener failed"), runner.OutcomeInconclusive}, + {"accepted", runner.Result{Outcome: runner.OutcomeVulnerable}, nil, runner.OutcomeVulnerable}, + } { + t.Run(test.name, func(t *testing.T) { + app := &application{run: func(_ context.Context, options runner.Options) (runner.Result, error) { + require.Equal(t, "/usr/bin/curl", options.Command[0]) + require.Equal(t, "-q", options.Command[1]) + return test.result, test.err + }} + steps := app.fixSteps(context.Background(), repair.Plan{}, "/tmp/empty", nil, false) + require.Len(t, steps, 2) + for _, step := range steps { + require.Equal(t, test.want, step.run().outcome) + } + }) + } +} diff --git a/cmd/embarass/root.go b/cmd/embarass/root.go index fb83008..e904a5d 100644 --- a/cmd/embarass/root.go +++ b/cmd/embarass/root.go @@ -55,6 +55,9 @@ func Execute() int { if app.headless { log := logger.Setup(app.verbose, command.ErrOrStderr()) log.Error().Err(err).Msg("emBarrass failed") + if errors.Is(err, errCommandRequired) { + app.logRepairCallToAction(&log) + } } else { ui := newTerminalUI(command.ErrOrStderr()) if errors.Is(err, errCommandRequired) { @@ -84,7 +87,12 @@ emBarrass routes one command through an authenticated local HTTPS interceptor. The interceptor is loopback-only except for the disclosed docker/git batch probe, which makes it reachable from that container. The tested client keeps its native CA configuration: emBarrass does not inject a CA file, disable verification, -forward intercepted traffic, or change the host trust store.`, +forward intercepted traffic, or change the host trust store. + +The explicit fix subcommand can apply a reversible emergency repair to supported +macOS and Linux CA stores. If you're completely or partially embarrassed, +preview the repair with fix --dry-run, apply with fix, then recheck with batch. +Private CA bundles and containers need separate updates.`, Example: fmt.Sprintf(` # Test individual tools with public, read-only requests %[1]s curl --silent https://example.com/ %[1]s git ls-remote https://github.com/actions/checkout.git HEAD @@ -97,6 +105,11 @@ forward intercepted traffic, or change the host trust store.`, %[1]s crane manifest registry.k8s.io/pause:3.10 # Preview and confirm installed-tool probes, including a container CA bundle + %[1]s batch + + # Embarrassed? Preview, repair, and recheck + %[1]s fix --dry-run + %[1]s fix %[1]s batch`, invocation), Args: func(_ *cobra.Command, args []string) error { if len(args) == 0 { @@ -120,7 +133,7 @@ forward intercepted traffic, or change the host trust store.`, registerChainCompletion(command) command.Flags().BoolVar(&app.headless, "headless", false, "emit compact log lines without the terminal UI") command.Flags().BoolVarP(&app.verbose, "verbose", "v", false, "enable debug logging") - command.AddCommand(newBatchCommand(app), newVersionCommand()) + command.AddCommand(newBatchCommand(app), newFixCommand(app), newFixCommitCommand(), newVersionCommand()) return command } @@ -158,6 +171,7 @@ func (app *application) runCheck(cmd *cobra.Command, args []string) error { } preparedCommand, adjustments := runner.PrepareCommand(args) ui := newTerminalUI(cmd.ErrOrStderr()) + ui.invocation = app.displayedInvocation() if !app.headless { if err := ui.start(args, chains, app.timeout, adjustments); err != nil { return err @@ -201,9 +215,21 @@ func (app *application) runCheck(cmd *cobra.Command, args []string) error { return ui.result(result, reportedChains, app.exitCode) } logHeadlessResult(zerolog.Ctx(cmd.Context()), result, reportedChains) + if result.Outcome == runner.OutcomeVulnerable { + app.logRepairCallToAction(zerolog.Ctx(cmd.Context())) + } return nil } +func (app *application) logRepairCallToAction(log *zerolog.Logger) { + invocation := app.displayedInvocation() + log.Warn(). + Str("preview", invocation+" fix --dry-run"). + Str("repair", invocation+" fix"). + Str("recheck", invocation+" batch"). + Msg("TAKE BACK TRUST: " + repairScope) +} + func logHeadlessAdjustments(log *zerolog.Logger, adjustments []runner.CommandAdjustment) { for _, adjustment := range adjustments { switch adjustment { diff --git a/cmd/embarass/terminal.go b/cmd/embarass/terminal.go index c5ab38b..b6e729e 100644 --- a/cmd/embarass/terminal.go +++ b/cmd/embarass/terminal.go @@ -44,6 +44,7 @@ type terminalUI struct { output io.Writer styles terminalStyles interactive bool + invocation string } type terminalStyles struct { @@ -124,7 +125,8 @@ func (ui terminalUI) start( if _, err := fmt.Fprintln( ui.output, - "\n\n CHILD OUTPUT "+strings.Repeat("─", 47), + "\n\n "+ui.styles.cyanBold.Render("EXPOSED?")+" Preview emergency repair: "+displayedInvocation(ui.invocation)+" fix --dry-run"+ + "\n\n CHILD OUTPUT "+strings.Repeat("─", 47), ); err != nil { return fmt.Errorf("write terminal child output separator: %w", err) } @@ -171,9 +173,24 @@ func (ui terminalUI) vulnerableResult( "", ) lines = append(lines, ui.resultMetadata(result, chains, exitCode)...) + lines = append(lines, "", repairCallToAction(ui.styles, ui.invocation, 72)) return strings.Join(lines, "\n") } +const repairScope = "Supported macOS/Linux system stores only. Private CA bundles and containers need separate updates." + +func repairCallToAction(styles terminalStyles, invocation string, width int) string { + invocation = displayedInvocation(invocation) + wrap := lipgloss.NewStyle().Width(max(24, width)).MarginLeft(2).Render + return strings.Join([]string{ + " " + styles.cyanBold.Render("TAKE BACK TRUST"), + wrap("Preview → " + styles.cyanBold.Render(invocation+" fix --dry-run")), + wrap("Repair → " + styles.greenBold.Render(invocation+" fix")), + wrap("Recheck → " + styles.cyanBold.Render(invocation+" batch")), + wrap(styles.muted.Render(repairScope)), + }, "\n") +} + func (ui terminalUI) rejectedResult( result runner.Result, chains []certforge.Chain, @@ -259,6 +276,8 @@ func (ui terminalUI) missingCommand(invocation string) error { " Or discover and safely test supported tools:", " " + ui.styles.greenBold.Render(invocation+" batch"), "", + repairCallToAction(ui.styles, invocation, 72), + "", " " + ui.styles.muted.Render("More examples: "+invocation+" --help"), ui.detail(ui.styles.bold, "EXIT", strconv.Itoa(exitInconclusive)), } diff --git a/docs/research/linux-emergency-fix.md b/docs/research/linux-emergency-fix.md new file mode 100644 index 0000000..465da27 --- /dev/null +++ b/docs/research/linux-emergency-fix.md @@ -0,0 +1,96 @@ +# Linux emergency distrust mechanisms + +Research snapshot: 2026-10-23. This note supports implementing the existing `fix` flow on Linux. It records native trust-store mechanisms; no system changes were applied during research. + +## Native providers + +| Family | Source of local policy | Regeneration | TLS bundle to inspect | +|---|---|---|---| +| Debian / Ubuntu | `/etc/ca-certificates.conf` deselection entries | `/usr/sbin/update-ca-certificates` | `/etc/ssl/certs/ca-certificates.crt` | +| Alpine with full `ca-certificates` | `/etc/ca-certificates.conf` deselection entries | `/usr/sbin/update-ca-certificates` | `/etc/ssl/certs/ca-certificates.crt` | +| Fedora / RHEL | `/etc/pki/ca-trust/source/blocklist/` (older installations: `blacklist/`) | `/usr/bin/update-ca-trust extract` | `/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem` | +| Arch | `/etc/ca-certificates/trust-source/blocklist/` | `/usr/bin/update-ca-trust extract` | `/etc/ca-certificates/extracted/tls-ca-bundle.pem` | +| openSUSE / SLES | `/etc/pki/trust/blocklist/` (older installations: `blacklist/`) | `update-ca-certificates` | Generated under `/var/lib/ca-certificates`; legacy `/etc/ssl/ca-bundle.pem` is an alias | + +The mechanisms and historical directory fallback are documented by the incident's upstream workaround. Debian, Alpine, Fedora and Arch package inventories independently establish the absolute updater paths above. For openSUSE, inspect the installed package rather than infer an executable location from its command name. [Incident workaround](https://emudhra.we-have-a-problem.com/#workarounds), [Debian inventory](https://packages.debian.org/trixie/all/ca-certificates/filelist), [Alpine inventory](https://pkgs.alpinelinux.org/contents?arch=loongarch64&branch=v3.22&name=ca-certificates&repo=main), [Fedora inventory](https://packages.fedoraproject.org/pkgs/ca-certificates/ca-certificates/fedora-43.html), [Arch inventory](https://archlinux.org/packages/core/any/ca-certificates-utils/files/) + +This is capability detection, not just distribution-name detection: check the policy inputs, updater, expected output, and file ownership before constructing a plan. Keep the initial supported families explicit; reject unknown layouts instead of editing whichever `cert.pem` happens to exist. + +## Debian and Ubuntu + +Prefix an enabled distribution certificate entry with `!` to deactivate it. Paths in `/etc/ca-certificates.conf` are relative to `/usr/share/ca-certificates`. Local `.crt` files under `/usr/local/share/ca-certificates` are included independently and implicitly trusted. The updater builds the PEM bundle and individual certificate collection; it invokes hooks in `/etc/ca-certificates/update.d` with added/removed certificate paths. `--fresh` removes generated symlinks. [Debian manual](https://manpages.debian.org/testing/ca-certificates/update-ca-certificates.8.en.html) + +The advisory names `mozilla/emSign_ECC_Root_CA_-_G3.crt` and `mozilla/Comodo_AAA_Services_root.crt`; identify certificates by the pinned DER fingerprints from [the macOS research](macos-emergency-fix.md), not filenames alone. Its Java caveat recommends a fresh `ca-certificates-java` rebuild when stores diverge. [Incident workaround](https://emudhra.we-have-a-problem.com/#workarounds) + +Implementation implications: + +- Parse every enabled source and local certificate. Disabling one distribution path does not remove another trusted copy of the same root. +- Preserve unrelated configuration. For a first implementation, refuse an ambiguous/local duplicate with its exact path before any mutation; alternatively implement an explicit, journaled quarantine for that file. Never silently report success while a duplicate survives. +- Store exact before/after configuration bytes and hashes. Refuse undo after configuration drift unless a deliberate merge can prove it changes only emBarrass-owned entries. Do not reintroduce entries removed or disabled by a vendor update. +- Run regeneration after apply and rollback. A successful PEM check alone does not certify independent Java stores or application-private stores; report coverage precisely. + +## Alpine + +Alpine packages distinguish `ca-certificates` from `ca-certificates-bundle`. The latter owns the generated PEM bundle and `/etc/ssl/cert.pem` symlink to `certs/ca-certificates.crt`. The full package generates `/etc/ca-certificates.conf`, installs the updater, and installs a `certhash` hook that runs `/usr/bin/c_rehash /etc/ssl/certs`. Package triggers watch certificate and hook directories. [Alpine package source](https://raw.githubusercontent.com/alpinelinux/aports/master/main/ca-certificates/APKBUILD) + +Minimal images can therefore have a usable TLS bundle without the policy/regeneration machinery. Treat that as a missing prerequisite; do not pretend the Debian-style provider is available. Current upstream GitLab implementation source was inaccessible during this review, so validate actual updater behavior in the target Alpine container, including local duplicates, idempotency, symlink regeneration, and hook failures. + +## Fedora and RHEL: explicit local distrust + +Red Hat documents `/etc/pki/ca-trust/source/blocklist/` as the administrator distrust directory, with higher-priority policy than the vendor's `/usr/share/pki/ca-trust-source/`. `update-ca-trust extract` updates the shared store used by supported NSS, GnuTLS, OpenSSL and Java consumers. [RHEL trust-store documentation](https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/securing_networks/using-shared-system-certificates_securing-networks) + +p11-kit treats certificates in its `blocklist/` directory as distrusted even without embedded trust flags. Merely placing a normal PEM in the parent directory gives neutral policy, and an `anchors/` directory gives positive trust. [p11-kit trust module](https://p11-glue.github.io/p11-glue/p11-kit/manual/trust-module.html) + +Create unique, emBarrass-owned PEM files containing the two verified target roots in the local distrust directory, then regenerate. Do not overwrite similarly named files already owned by an administrator or package. This avoids editing the vendor bundle and makes undo narrow: remove only files created by the recorded transaction after verifying their hashes, then regenerate from current vendor policy. A vendor update applied after the repair is naturally preserved. + +Legacy paths may be symlinks to generated output. Fedora's package history explicitly records changes and restoration of aliases such as `/etc/ssl/cert.pem` and `/etc/pki/tls/certs/ca-bundle.crt`. Verify the installed layout; do not replace aliases with regular files. [Fedora package history](https://packages.fedoraproject.org/pkgs/ca-certificates/ca-certificates/fedora-43.html) + +## Arch and openSUSE differences + +Arch provides the same broad policy model at different paths. Its manual explicitly says generated outputs must not be edited. Simple PEM and Java output omit distrusted roots; the extended OpenSSL bundle may retain certificates with rejection flags. Therefore a certificate's presence in the extended bundle is not evidence of positive trust. `/etc/ssl/cert.pem`, legacy bundle aliases, Java aliases, and hashed certificates refer to generated output. [Arch manual](https://man.archlinux.org/man/update-ca-trust.8.en) + +openSUSE's source says `/etc/ca-certificates.conf` is unsupported. p11-kit policy under `/etc/pki/trust` drives generated stores, and every store is produced by hooks. Its updater processes `.run` hooks under `/etc/ca-certificates/update.d` and `/usr/lib/ca-certificates/update.d`; this differs from Debian despite sharing the command name. [openSUSE README](https://raw.githubusercontent.com/openSUSE/ca-certificates/master/README), [updater source](https://raw.githubusercontent.com/openSUSE/ca-certificates/master/update-ca-certificates) + +## Transaction and verification recommendations + +These are engineering recommendations: + +1. Pin certificate identity, inventory all applicable source inputs, and preflight the entire plan before changing anything. +2. Execute only the known root-owned regeneration tool with a controlled environment and PATH. Its administrator-installed hooks remain part of the native update operation; capture their output and failures. +3. Journal source changes before applying them. Native regeneration updates multiple files and hooks; do not describe the whole transaction as atomic. +4. Validate generated TLS anchors and the hashed-directory view; do not parse an extended trust bundle as an ordinary positive-only bundle. Preserve unrelated trust and enterprise roots. +5. On regeneration/integrity failure, undo only owned source changes and regenerate again. If recovery fails, retain the journal and report the incomplete state rather than success. +6. Undo must regenerate from current sources, never copy an old generated bundle over a later vendor update. A drift refusal is preferable to guessing ownership. +7. Keep filesystem repair status separate from actual client tests. Run both emSign and AAA paths unprivileged, and report independently configured tools or containers separately. + +This emergency patch remains compatible with recommending normal vendor updates. Its immediate job is to apply native local distrust wherever the required policy and regeneration machinery already exists. + +## Implementation validation + +On 2026-10-23, `pkg/repair/testdata/native-smoke.sh` passed in disposable arm64 +containers built from these official image digests: + +- Debian bookworm-slim: `sha256:7ff6ba31527b9e336162fa061746c366c4b2032f4d2cff2078bea43f78efe3f8` +- Alpine: `sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a` +- Fedora: `sha256:43b29f65a41eb9c35e1cd5323e3bdf3b655c2357a9f4f1ff2f9c2798e5045d80` + +The images install current native CA tools, curl, OpenSSL, and `su`; they seed +public vulnerable roots solely inside the container. Tests run without external +network access or host mounts. They verify a read-only preview, native repair, +both forged paths through curl's default store, the unprivileged `fix` verdict, +preservation of an unrelated enterprise root, no-op inspection, and undo. +Fedora additionally retains a simulated vendor distrust update across undo. +Ubuntu and the RHEL derivatives were not separately exercised. + +These tests exposed two verification details. The runner must wait for active +TLS handlers after child exit instead of draining their observations early. +Also, the newer Alpine and Fedora curl builds completed the handshake before +exiting 60 and resetting the connection without a TLS rejection alert. The +generic wrapper correctly leaves that case inconclusive; the controlled `fix` +probe can combine observed tunnel traffic with curl's explicit peer-verification +exit code. Generic TLS errors, unobserved failures, and timeouts remain +inconclusive. [curl error-code documentation](https://curl.se/libcurl/c/libcurl-errors.html) + +The full Go race-enabled suite and lint passed. macOS was checked with a +read-only system dry run and temporary-bundle tests; no host trust changes were +applied during this validation. diff --git a/docs/research/macos-emergency-fix.md b/docs/research/macos-emergency-fix.md new file mode 100644 index 0000000..8a60c76 --- /dev/null +++ b/docs/research/macos-emergency-fix.md @@ -0,0 +1,91 @@ +# macOS emergency trust-bundle repair + +Research snapshot: 2026-10-23. This is a source review and proposed design, not an applied system repair. + +## Current vendor status and platform scope + +Rechecked 2026-10-23: the live incident advisory dates Apple's intermediate blocking to October 22, while still explicitly describing `/etc/ssl/cert.pem` as unpatched. Those are separate mechanisms; native trust mitigation does not establish that the PEM bundle changed. [Live advisory](https://emudhra.we-have-a-problem.com/) + +Apple's current security-release index lists macOS 27.0.1, 26.7.1, and 15.8.1 releases dated September 28. Apple also documents security configuration and system-data updates between OS releases. Therefore the release dates alone cannot establish whether a fix reached every device. No Apple-issued notice confirming an eMudhra update to `/etc/ssl/cert.pem` was found in this review. The local file observation below establishes only this Mac's contents. [Apple security releases](https://support.apple.com/en-us/100100), [Apple background updates](https://support.apple.com/en-us/101591) + +Native Apple trust also needs careful wording. Upstream issue #69 records incomplete rejection on October 21–22, then multiple October 23 reports of all test chains being rejected without local changes. Reporters associate the improvement with the OCSP responder recovering and question whether blocking is unconditional. Separately, the advisory maintainer explains that CT would exclude the reported non-test-domain certificates from Apple browser trust, and that Apple-trusted CT logs had stopped accepting these intermediates by October 21. These observations concern different layers; they do not prove general Safari exploitability or a PEM-file fix. Treat the issue as evolving evidence and test the actual client. [Upstream issue #69, including October 23 updates](https://github.com/galadran/we-have-a-problem.com/issues/69) + +Linux already has vendor package fixes. These are verified examples, not an exhaustive supported-version matrix: + +| Platform | Current primary-source evidence | Preferred remediation mechanism | +|---|---|---| +| Debian | The issue records `20260816+nmu1` and `20250419+deb13u1`, blacklisting the two roots. [Debian bug #1151413](https://bugs.debian.org/1151413) | Upgrade the distribution's `ca-certificates` package. | +| Alpine | Its package index lists `20261020-r0`. [Alpine package index](https://pkgs.alpinelinux.org/packages?name=ca-certificates&arch=) | Upgrade `ca-certificates` in each affected image/system. | +| RHEL 9 | The vendor erratum supplies `2026.2.92_v9.0.319-90.3.el9_8`. [RHSA-2026:88459](https://access.redhat.com/errata/RHSA-2026:88459) | Install the applicable supported release's vendor update. | +| Arch | The live repository now lists `ca-certificates-mozilla` `3.132-1`, newer than the incident's initial fixed version. [Arch package page](https://archlinux.org/packages/core/x86_64/ca-certificates-mozilla/) | Update through the distribution's normal package workflow. | +| Ubuntu | The incident advisory lists fixed `ca-certificates` versions for 22.04, 24.04, 26.04, and 26.10; its linked Launchpad evidence was inaccessible during this review. [Advisory version table](https://emudhra.we-have-a-problem.com/#who-has-patched) | Use the distribution package update; verify the installed version and behavior. | + +Engineering recommendation: share the diagnosis and plan interface across platforms, but use separate remediation providers. macOS needs this narrowly scoped emergency bundle edit; Linux should prefer vendor package updates, which own bundle generation and other store integration. Do not directly edit a generated Linux PEM bundle as a universal fix. Images, runtime-embedded roots, and user-specific bundles remain distinct repair targets. A host package update cannot be treated as proof that every container or application changed. + +## What WardLatch does + +WardLatch implements the advisory's macOS workaround: remove `AAA Certificate Services` and `emSign ECC Root CA - G3` from `/etc/ssl/cert.pem`. The advisory identifies this file as the separate trust source for Apple's built-in curl, git, Python, Perl, Ruby, and OpenSSL. It also publishes distinct direct and AAA-cross-signed test endpoints; checking one path does not exercise the other. [Original advisory](https://emudhra.we-have-a-problem.com/#are-there-workarounds-until-patches-are-available) + +The upstream discussion records before/after measurements on macOS 26.7.1 for curl, git, Python, and OpenSSL, with nscurl as the system-trust comparison. Filippo Valsorda's merged October 21 change expanded the advisory and documented Apple's pip distinction. These sources establish the workaround's scope more directly than WardLatch's marketing page. [Issue #45](https://github.com/galadran/we-have-a-problem.com/issues/45), [PR #52](https://github.com/galadran/we-have-a-problem.com/pull/52) + +The reviewed script: + +- Requires Darwin and a file containing at least 50 certificate markers. +- Matches Apple-format comment headers by CN, then removes the corresponding sections using awk. +- Checks marker counts and absence of matching headers, without parsing certificates. +- Creates a timestamped `cp -p` backup after checking the name is unused. +- Copies the temporary output over the live file with `cp`, then sets mode 0644. This is not an atomic replacement. +- Tests only the direct DV-G3B endpoint with `/usr/bin/curl --cacert`. +- Restores the backup only when that test connects successfully. Other curl failures still produce a SAFE message qualified as unverified online. +- Has no rollback trap for write/chmod failure; its exit trap only deletes the temporary file. +- Provides a manual restore command and no-ops when matching headers are absent. + +These are observations of source, not guarantees inferred from the landing page. [WardLatch script](https://github.com/deimos-hq/wardlatch/blob/main/fix/fix-macos.sh) + +Its curl invocation also omits `-q`. curl documents that `-q` must be the first argument to suppress curlrc loading, so user configuration can affect this check. [curl manual](https://curl.se/docs/manpage.html#-q) + +## Certificate identities + +The advisory's machine-readable root inventory supplies these SHA-256 fingerprints of the complete DER certificate: + +| Certificate | SHA-256(DER) | +|---|---| +| AAA Certificate Services | `D7A7A0FB5D7E2731D771E9484EBCDEF71D5F0C3E0A2948782BC83EE0EA699EF4` | +| emSign ECC Root CA - G3 | `86A1ECBA089C4A8D3BBE2734C612BA341D813E043CF9E8A862CD5C57A36BBE6B` | + +The inventory also includes `emSign Root TLS CA - G3` and `emSign Root CS CA - G3`, marked as not included in Apple's root store. Therefore these two removals are a specifically scoped Apple-bundle workaround, not a universal cleanup rule for arbitrary custom stores. [Root inventory](https://emudhra.we-have-a-problem.com/roots.json) + +Local read-only observation on 2026-10-23: this workspace's Mac has 128 PEM certificates in `/etc/ssl/cert.pem`, including both exact fingerprints above. This establishes file contents, not the runtime vulnerability of any specific tool. + +Removing trust anchors removes trust in every otherwise-valid path relying solely on those anchors, not just the compromised intermediate keys. This is an engineering consequence of root removal and should be visible in the proposed change summary. + +## pip is a separate change + +The advisory says Apple's built-in pip and environments created from Apple's Python use their own old root bundle. Its additional command appends Python code to `sitecustomize.py` to default `PIP_CERT` to `/etc/ssl/cert.pem`. This is separate from repairing the PEM file. [Original workaround](https://emudhra.we-have-a-problem.com/#are-there-workarounds-until-patches-are-available) + +`sitecustomize` is Python startup customization, so editing it affects more than a single pip command. `PIP_CERT` is a documented pip bundle override. Prefer reporting this remaining exposure and handling it as an explicit, separately reversible action; do not silently append global startup code in the first bundle repair. [Python site documentation](https://docs.python.org/3/library/site.html#module-sitecustomize), [pip certificate configuration](https://pip.pypa.io/en/stable/topics/https-certificates/) + +## Proposed emBarrass interface and requirements + +These are design recommendations, not claims about WardLatch: + +```text +embarass fix --dry-run # show exact file, certificates, and affected scope +embarass fix # show plan, confirm, apply, verify +embarass fix --yes # apply the same plan noninteractively +embarass fix --undo # restore a recorded repair with conflict detection +``` + +Keep `batch` as the behavioral check. `fix` clearly signals mutation; reserve `doctor` for diagnosis if broader environment analysis becomes necessary. Avoid promising that a bundle repair fixes every installed tool. + +For the initial macOS implementation: + +1. Parse PEM and X.509 certificates; identify removal targets by pinned certificate fingerprints. Preserve unrelated certificates and content, including enterprise roots. Reject malformed or ambiguous input. +2. Restrict writes to the known system bundle. Handle its resolved path deliberately; reject unexpected symlinks, ownership, or writable parent directories. Never run discovered PATH programs or Python startup hooks as root. +3. Create an exclusive backup and journal with original/replacement hashes and metadata. Stage on the same filesystem, validate the exact resulting certificate set, flush, then atomically replace. Detect concurrent modification before commit. +4. Separate file verification from behavioral verification. Exercise both trust paths using the existing local interception machinery and appropriate unprivileged clients. A patched Go verifier can reject compromised intermediates even with an unpatched bundle, so its rejection alone cannot validate this repair. +5. Report `applied`, `already applied`, `verification inconclusive`, and `still exposed` distinctly. An unrelated connection failure is not evidence of protection. If a file invariant fails, restore transactionally; do not silently undo a valid removal merely because one independently configured tool remains exposed. +6. Undo only when the current file still matches the recorded replacement, so a later vendor update or administrator edit is not overwritten. Explain that undo reintroduces the original trust anchors. +7. Re-run normal-user batch checks after the narrow repair and list remaining exposures with targeted next steps. Exclude the deliberately vulnerable historical Docker/Git fixture from host-repair success criteria. Updates may replace system files, so rechecking remains necessary. + +The first release should repair only this known bundle. Separate runtime bundles, package upgrades, and global per-tool configuration need their own detection, review, and rollback contracts. diff --git a/go.mod b/go.mod index c9684ef..401ac3f 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/lipgloss v1.1.0 github.com/mattn/go-isatty v0.0.20 + github.com/muesli/termenv v0.16.0 github.com/rs/zerolog v1.34.0 github.com/spf13/cobra v1.10.1 github.com/stretchr/testify v1.11.1 @@ -26,7 +27,6 @@ require ( github.com/mattn/go-runewidth v0.0.16 // indirect github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect - github.com/muesli/termenv v0.16.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/spf13/pflag v1.0.10 // indirect diff --git a/pkg/repair/bundle.go b/pkg/repair/bundle.go new file mode 100644 index 0000000..46c2d74 --- /dev/null +++ b/pkg/repair/bundle.go @@ -0,0 +1,170 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package repair implements narrowly scoped, reversible system CA repairs. +package repair + +import ( + "bytes" + "crypto/sha256" + "crypto/x509" + "encoding/asn1" + "encoding/hex" + "encoding/pem" + "errors" + "fmt" +) + +// BundlePath is the sole production repair target. /etc is a macOS symlink. +const BundlePath = "/private/etc/ssl/cert.pem" + +// Root identifies an exact certificate, rather than a comment or subject name. +type Root struct { + Name string `json:"name"` + SHA256 string `json:"sha256"` +} + +var affectedRoots = []Root{ + {"AAA Certificate Services", "d7a7a0fb5d7e2731d771e9484ebcdef71d5f0c3e0a2948782bc83ee0ea699ef4"}, + {"emSign ECC Root CA - G3", "86a1ecba089c4a8d3bbe2734c612ba341d813e043cf9e8a862cd5c57a36bbe6b"}, +} + +// Plan is an immutable snapshot. Apply checks its input hash again under a lock. +type Plan struct { + Path string + BundlePath string + Platform string + Refresh string + BeforeSHA256 string + AfterSHA256 string + Certificates int + Removed []Root + original []byte + replacement []byte +} + +func digest(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +// inspect parses every PEM block and preserves all bytes outside removed blocks. +// Apple includes descriptive text between certificates; it is not trust data. +func inspect(data []byte) (Plan, error) { + plan := Plan{BeforeSHA256: digest(data), original: bytes.Clone(data)} + rest := data + for len(rest) > 0 { + start := bytes.Index(rest, []byte("-----BEGIN ")) + if start < 0 { + if bytes.Contains(rest, []byte("-----END ")) { + return Plan{}, errors.New("unmatched PEM end marker") + } + plan.replacement = append(plan.replacement, rest...) + break + } + prefix := rest[:start] + if bytes.Contains(prefix, []byte("-----END ")) { + return Plan{}, errors.New("unmatched PEM end marker") + } + end := bytes.Index(rest[start:], []byte("-----END CERTIFICATE-----")) + if end < 0 { + return Plan{}, errors.New("unterminated or unsupported PEM block") + } + end += start + len("-----END CERTIFICATE-----") + encoded := rest[start:end] + if bytes.Count(encoded, []byte("-----BEGIN ")) != 1 { + return Plan{}, errors.New("nested or malformed PEM block") + } + block, trailing := pem.Decode(encoded) + if block == nil || block.Type != "CERTIFICATE" || len(block.Headers) != 0 || len(trailing) != 0 { + return Plan{}, errors.New("malformed or unsupported certificate PEM") + } + cert, err := parseBundleCertificate(block.Bytes) + if err != nil { + return Plan{}, fmt.Errorf("parse bundle certificate: %w", err) + } + plan.Certificates++ + fingerprint := digest(block.Bytes) + remove := false + for _, root := range affectedRoots { + if fingerprint == root.SHA256 { + plan.Removed = append(plan.Removed, root) + remove = true + break + } + if cert.Subject.CommonName == root.Name { + return Plan{}, fmt.Errorf("unexpected fingerprint for %s; refusing an ambiguous repair", root.Name) + } + } + plan.replacement = append(plan.replacement, prefix...) + if !remove { + plan.replacement = append(plan.replacement, encoded...) + } + rest = rest[end:] + } + if plan.Certificates == 0 || plan.Certificates == len(plan.Removed) { + return Plan{}, errors.New("repair would leave no trusted certificates") + } + plan.AfterSHA256 = digest(plan.replacement) + return plan, nil +} + +// Apple still ships a legacy root with a negative ASN.1 serial. Modern Go +// rejects it by default. Validate a positive-serial COPY in that one case; +// never change the bundle's DER, fingerprint the copy, or use it for trust +// verification. This avoids changing process-wide GODEBUG parser policy. +func parseBundleCertificate(der []byte) (*x509.Certificate, error) { + cert, originalErr := x509.ParseCertificate(der) + if originalErr == nil { + return cert, nil + } + originalErr = fmt.Errorf("parse X.509 certificate: %w", originalErr) + var outer, tbs, first, serial asn1.RawValue + rest, err := asn1.Unmarshal(der, &outer) + if err != nil || len(rest) != 0 || outer.Tag != asn1.TagSequence || outer.Class != asn1.ClassUniversal { + return nil, originalErr + } + tail, err := asn1.Unmarshal(outer.Bytes, &tbs) + if err != nil || tbs.Tag != asn1.TagSequence || tbs.Class != asn1.ClassUniversal { + return nil, originalErr + } + afterFirst, err := asn1.Unmarshal(tbs.Bytes, &first) + if err != nil { + return nil, originalErr + } + prefix := []byte(nil) + serial, rest = first, afterFirst + if first.Class == asn1.ClassContextSpecific && first.Tag == 0 { + prefix = first.FullBytes + rest, err = asn1.Unmarshal(afterFirst, &serial) + if err != nil { + return nil, originalErr + } + } + if serial.Class != asn1.ClassUniversal || serial.Tag != asn1.TagInteger || serial.IsCompound || len(serial.Bytes) == 0 || serial.Bytes[0]&0x80 == 0 { + return nil, originalErr + } + serial.FullBytes = nil + serial.Bytes = append([]byte{0}, serial.Bytes...) + encoded, err := asn1.Marshal(serial) + if err != nil { + return nil, originalErr + } + tbs.FullBytes = nil + tbs.Bytes = append(append(bytes.Clone(prefix), encoded...), rest...) + encoded, err = asn1.Marshal(tbs) + if err != nil { + return nil, originalErr + } + outer.FullBytes = nil + outer.Bytes = append(encoded, tail...) + encoded, err = asn1.Marshal(outer) + if err != nil { + return nil, originalErr + } + cert, err = x509.ParseCertificate(encoded) + if err != nil { + return nil, originalErr + } + return cert, nil +} diff --git a/pkg/repair/bundle_test.go b/pkg/repair/bundle_test.go new file mode 100644 index 0000000..f620355 --- /dev/null +++ b/pkg/repair/bundle_test.go @@ -0,0 +1,108 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package repair + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "os" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func ordinaryRoot(t *testing.T, name string) []byte { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + cert := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} + der, err := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key) + require.NoError(t, err) + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) +} + +func affectedRoot(t *testing.T, name string) []byte { + t.Helper() + data, err := os.ReadFile("testdata/" + name + ".pem") + require.NoError(t, err) + return data +} + +func fixtureBundle(t *testing.T) []byte { + t.Helper() + data := []byte("# enterprise roots must survive byte-for-byte\n") + data = append(data, ordinaryRoot(t, "Enterprise test root")...) + data = append(data, affectedRoot(t, "aaa")...) + return append(data, affectedRoot(t, "emsign")...) +} + +func TestInspectRemovesExactCertificatesPreservingOtherBytes(t *testing.T) { + t.Parallel() + trusted := ordinaryRoot(t, "Enterprise test root") + before := "### metadata\r\n" + between := "\r\n# not a trust anchor\n" + after := "\n# end of bundle\n" + data := append([]byte(before), trusted...) + data = append(data, []byte(between)...) + data = append(data, affectedRoot(t, "aaa")...) + data = append(data, affectedRoot(t, "emsign")...) + data = append(data, []byte(after)...) + plan, err := inspect(data) + require.NoError(t, err) + require.Len(t, plan.Removed, 2) + require.Equal(t, 3, plan.Certificates) + require.Equal(t, before+string(trusted)+between+"\n\n"+after, string(plan.replacement)) + again, err := inspect(plan.replacement) + require.NoError(t, err) + require.Empty(t, again.Removed) + require.Equal(t, again.original, again.replacement) +} + +func TestInspectRejectsMalformedAndAmbiguousBundles(t *testing.T) { + t.Parallel() + valid := ordinaryRoot(t, "unrelated") + for name, data := range map[string][]byte{ + "empty": {}, + "no survivors": affectedRoot(t, "aaa"), + "truncated": append(append([]byte{}, valid...), []byte("-----BEGIN CERTIFICATE-----\nbroken")...), + "stray end": append(append([]byte{}, valid...), []byte("-----END CERTIFICATE-----")...), + "malformed before valid": append([]byte("-----BEGIN CERTIFICATE-----\nbroken\n"), valid...), + "wrong certificate type": append(append([]byte{}, valid...), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte{1, 2, 3}})...), + "same subject different key": append(append([]byte{}, valid...), ordinaryRoot(t, "AAA Certificate Services")...), + } { + t.Run(name, func(t *testing.T) { _, err := inspect(data); require.Error(t, err) }) + } +} + +func TestInspectRemovesDuplicateAffectedCertificates(t *testing.T) { + t.Parallel() + data := append(fixtureBundle(t), affectedRoot(t, "aaa")...) + plan, err := inspect(data) + require.NoError(t, err) + require.Len(t, plan.Removed, 3) + require.Equal(t, 4, plan.Certificates) +} + +func TestLegacyNegativeSerialRootIsPreservedExactly(t *testing.T) { + t.Parallel() + legacy := affectedRoot(t, "legacy-negative-serial") + data := append(append([]byte{}, legacy...), affectedRoot(t, "aaa")...) + plan, err := inspect(data) + require.NoError(t, err) + require.Len(t, plan.Removed, 1) + require.Equal(t, string(legacy)+"\n", string(plan.replacement)) + block, _ := pem.Decode(legacy) + before := append([]byte{}, block.Bytes...) + _, err = parseBundleCertificate(block.Bytes) + require.NoError(t, err) + require.Equal(t, before, block.Bytes, "compatibility validation must never mutate input DER") +} diff --git a/pkg/repair/files_other.go b/pkg/repair/files_other.go new file mode 100644 index 0000000..520318f --- /dev/null +++ b/pkg/repair/files_other.go @@ -0,0 +1,19 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later +//go:build !darwin && !linux + +package repair + +import ( + "errors" + "os" +) + +func ownedBy(_ os.FileInfo, _ int) bool { return false } +func preserveOwner(_ *os.File, _ os.FileInfo) error { return errors.New("unsupported platform") } +func readSecure(_ string, _ bool) ([]byte, os.FileInfo, error) { + return nil, nil, errors.New("system bundle repair is unsupported on this platform") +} +func lockStore(_ string) (func(), error) { + return nil, errors.New("system bundle repair is unsupported on this platform") +} diff --git a/pkg/repair/files_unix.go b/pkg/repair/files_unix.go new file mode 100644 index 0000000..7d6cf94 --- /dev/null +++ b/pkg/repair/files_unix.go @@ -0,0 +1,72 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later +//go:build darwin || linux + +package repair + +import ( + "errors" + "fmt" + "io" + "os" + "syscall" + + "golang.org/x/sys/unix" +) + +func ownedBy(info os.FileInfo, uid int) bool { + stat, ok := info.Sys().(*syscall.Stat_t) + return ok && stat.Uid == uint32(uid) && (!info.Mode().IsRegular() || stat.Nlink == 1) +} + +func preserveOwner(file *os.File, info os.FileInfo) error { + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return errors.New("cannot read original bundle ownership") + } + if err := file.Chown(int(stat.Uid), int(stat.Gid)); err != nil { + return fmt.Errorf("preserve bundle ownership: %w", err) + } + return nil +} + +func readSecure(path string, requireOwner bool) ([]byte, os.FileInfo, error) { + file, err := os.OpenFile(path, os.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) + if err != nil { + return nil, nil, fmt.Errorf("open %s: %w", path, err) + } + defer func() { _ = file.Close() }() + info, err := file.Stat() + if err != nil { + return nil, nil, fmt.Errorf("stat %s: %w", path, err) + } + if !info.Mode().IsRegular() || info.Mode().Perm()&0022 != 0 || (requireOwner && !ownedBy(info, os.Geteuid())) { + return nil, nil, fmt.Errorf("unsafe ownership, permissions, or file type: %s", path) + } + const maximum = 10 << 20 + data, err := io.ReadAll(io.LimitReader(file, maximum+1)) + if err != nil { + return nil, nil, fmt.Errorf("read %s: %w", path, err) + } + if len(data) > maximum { + return nil, nil, errors.New("bundle or receipt exceeds 10 MiB") + } + return data, info, nil +} + +func lockStore(path string) (func(), error) { + file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0600) + if err != nil { + return nil, fmt.Errorf("open repair lock: %w", err) + } + info, err := file.Stat() + if err != nil || !info.Mode().IsRegular() || !ownedBy(info, os.Geteuid()) || info.Mode().Perm() != 0600 { + _ = file.Close() + return nil, errors.New("unsafe repair lock") + } + if err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + _ = file.Close() + return nil, fmt.Errorf("another repair is running: %w", err) + } + return func() { _ = file.Close() }, nil +} diff --git a/pkg/repair/linux.go b/pkg/repair/linux.go new file mode 100644 index 0000000..b2a2ffe --- /dev/null +++ b/pkg/repair/linux.go @@ -0,0 +1,696 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package repair + +import ( + "bytes" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "time" +) + +type linuxSpec struct { + family, label, bundle, config, sources, local, blocklist, updater, state, root string + args []string +} + +type linuxStore struct { + spec linuxSpec + owner int + rebuild func() error +} + +type nativeEdit struct { + Path string `json:"path"` + Existed bool `json:"existed"` + Before []byte `json:"before,omitempty"` + After []byte `json:"after"` + Mode uint32 `json:"mode"` + Sources map[string]string `json:"sources,omitempty"` +} + +type nativeRecord struct { + Version int `json:"version"` + Family string `json:"family"` + Created string `json:"created"` + Bundle string `json:"bundle"` + BundleBefore []byte `json:"bundle_before"` + Roots []Root `json:"roots"` + Edits []nativeEdit `json:"edits"` +} + +type nativePlan struct { + Plan + edits []nativeEdit + bundle []byte +} + +func linuxSystem() (*linuxStore, error) { + // os-release is data, never sourced as a shell program. + path, err := filepath.EvalSymlinks("/etc/os-release") + if err != nil { + return nil, fmt.Errorf("locate Linux release information: %w", err) + } + if err = trustedParents(path, "/", 0); err != nil { + return nil, err + } + data, info, err := readSecure(path, false) + if err != nil { + return nil, err + } + if !ownedBy(info, 0) { + return nil, errors.New("untrusted Linux release information") + } + id := "" + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, "ID=") { + id = strings.Trim(strings.TrimPrefix(line, "ID="), "\"'") + } + } + spec, err := linuxLayout(id) + if err != nil { + return nil, err + } + store := &linuxStore{spec: spec} + if spec.family == "p11-kit" { + if _, err := os.Stat(spec.blocklist); os.IsNotExist(err) { + store.spec.blocklist = "/etc/pki/ca-trust/source/blacklist" + } + } + return store, nil +} + +func linuxLayout(id string) (linuxSpec, error) { + spec := linuxSpec{root: "/", state: "/etc/embarass-fix", args: nil} + switch id { + case "debian", "ubuntu", "alpine": + spec.family, spec.label = "debian", id+" native CA configuration" + spec.bundle, spec.config = "/etc/ssl/certs/ca-certificates.crt", "/etc/ca-certificates.conf" + spec.sources, spec.local = "/usr/share/ca-certificates", "/usr/local/share/ca-certificates" + spec.updater = "/usr/sbin/update-ca-certificates" + case "fedora", "rhel", "centos", "rocky", "almalinux", "amzn", "ol": + spec.family, spec.label = "p11-kit", id+" native CA distrust" + spec.bundle = "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" + spec.blocklist = "/etc/pki/ca-trust/source/blocklist" + spec.updater, spec.args = "/usr/bin/update-ca-trust", []string{"extract"} + default: + return spec, fmt.Errorf("unsupported Linux distribution %q; update its CA packages and use batch to verify", id) + } + return spec, nil +} + +func (s *linuxStore) Inspect() (Plan, error) { + plan, err := s.prepare() + return plan.Plan, err +} + +// Native helpers execute root-owned distro hooks. The preview discloses this; +// the caller never supplies a command, environment, source root, or hook path. +func (s *linuxStore) validate() error { + paths := []string{s.spec.bundle, s.spec.updater, s.spec.state} + if s.spec.config != "" { + paths = append(paths, s.spec.config) + } + if s.spec.blocklist != "" { + paths = append(paths, filepath.Join(s.spec.blocklist, "probe.pem")) + } + for _, path := range paths { + if err := trustedParents(path, s.spec.root, s.owner); err != nil { + return err + } + } + _, info, err := readSecure(s.spec.updater, false) + if err != nil { + return fmt.Errorf("native CA updater is required; install/update the full ca-certificates package first: %w", err) + } + if !ownedBy(info, s.owner) || info.Mode().Perm()&0111 == 0 { + return errors.New("untrusted native CA updater") + } + return nil +} + +func trustedParents(path, root string, owner int) error { + dir, err := filepath.EvalSymlinks(filepath.Dir(path)) + if err != nil { + return fmt.Errorf("resolve native store directory: %w", err) + } + root, err = filepath.EvalSymlinks(root) + if err != nil { + return fmt.Errorf("resolve native store root: %w", err) + } + if dir != root && !strings.HasPrefix(dir, strings.TrimSuffix(root, "/")+"/") { + return errors.New("native store path escapes its root") + } + for { + info, err := os.Lstat(dir) + if err != nil { + return fmt.Errorf("inspect native store directory: %w", err) + } + if !info.IsDir() || !ownedBy(info, owner) || info.Mode().Perm()&0022 != 0 { + return fmt.Errorf("unsafe native store directory: %s", dir) + } + if dir == root { + return nil + } + dir = filepath.Dir(dir) + } +} + +func (s *linuxStore) read(path string) ([]byte, os.FileInfo, error) { + if err := trustedParents(path, s.spec.root, s.owner); err != nil { + return nil, nil, err + } + data, info, err := readSecure(path, false) + if err != nil { + return nil, nil, err + } + if !ownedBy(info, s.owner) { + return nil, nil, fmt.Errorf("unexpected native store file owner: %s", path) + } + if info.Mode().Perm()&0004 == 0 { + return nil, nil, fmt.Errorf("private native CA files need manual handling: %s", path) + } + return data, info, nil +} + +func (s *linuxStore) prepare() (nativePlan, error) { + var result nativePlan + if err := s.validate(); err != nil { + return result, err + } + bundle, _, err := s.read(s.spec.bundle) + if err != nil { + return result, err + } + plan, err := inspect(bundle) + if err != nil { + return result, err + } + plan.BundlePath, plan.Platform = s.spec.bundle, s.spec.label + plan.Refresh = strings.Join(append([]string{s.spec.updater}, s.spec.args...), " ") + result.Plan, result.bundle = plan, bundle + var snapshot bytes.Buffer + snapshot.WriteString(digest(bundle)) + if s.spec.family == "debian" { + result.Path = s.spec.config + edits, roots, err := s.debianEdits(&snapshot) + if err != nil { + return result, err + } + result.edits = edits + result.Removed = uniqueRoots(append(result.Removed, roots...)) + } else { + result.Path = s.spec.blocklist + blocks, err := certificateBlocks(bundle) + if err != nil { + return result, err + } + for _, root := range uniqueRoots(result.Removed) { + path := filepath.Join(s.spec.blocklist, "embarass-"+root.SHA256+".pem") + before, _, err := s.read(path) + snapshot.WriteString(path) + if err == nil { + snapshot.WriteString(digest(before)) + known, parseErr := certificateBlocks(before) + if parseErr != nil || len(known) != 1 || known[root.SHA256] == nil { + return result, fmt.Errorf("conflicting native distrust file: %s", path) + } + continue // Pre-existing policy is never claimed or removed by undo. + } + if !errors.Is(err, os.ErrNotExist) { + return result, err + } + snapshot.WriteString("absent") + result.edits = append(result.edits, nativeEdit{Path: path, After: blocks[root.SHA256], Mode: 0644}) + } + } + result.BeforeSHA256 = digest(snapshot.Bytes()) + return result, nil +} + +func (s *linuxStore) debianEdits(snapshot *bytes.Buffer) ([]nativeEdit, []Root, error) { + config, info, err := s.read(s.spec.config) + if err != nil { + return nil, nil, fmt.Errorf("native CA configuration is required; install/update the full ca-certificates package first: %w", err) + } + snapshot.WriteString(digest(config)) + var out bytes.Buffer + var roots []Root + sources := make(map[string]string) + for _, line := range strings.SplitAfter(string(config), "\n") { + entry := strings.TrimSpace(line) + disabled := strings.HasPrefix(entry, "!") + if entry == "" || strings.HasPrefix(entry, "#") { + out.WriteString(line) + continue + } + entry = strings.TrimPrefix(entry, "!") + if filepath.IsAbs(entry) || filepath.Clean(entry) != entry || strings.HasPrefix(entry, "..") || !strings.HasSuffix(entry, ".crt") { + return nil, nil, fmt.Errorf("unsupported CA configuration entry %q", entry) + } + path := filepath.Join(s.spec.sources, entry) + cert, _, readErr := s.read(path) + snapshot.WriteString(path) + if readErr != nil { + if !errors.Is(readErr, os.ErrNotExist) { + return nil, nil, readErr + } + snapshot.WriteString("absent") + out.WriteString(line) + continue // Native updaters also tolerate removed vendor source files. + } + snapshot.WriteString(digest(cert)) + found, err := matchingRoots(cert) + if err != nil { + return nil, nil, fmt.Errorf("inspect native CA source %s: %w", path, err) + } + if len(found) > 0 && !disabled { + blocks, err := certificateBlocks(cert) + if err != nil || len(blocks) != len(found) { + return nil, nil, fmt.Errorf("CA source mixes affected and unrelated certificates: %s", path) + } + roots = append(roots, found...) + sources[path] = digest(cert) + // Preserve whitespace/comments everywhere except this exact entry. + position := strings.Index(line, entry) + out.WriteString(line[:position] + "!" + line[position:]) + } else { + out.WriteString(line) + } + } + if err := s.checkLocalRoots(snapshot); err != nil { + return nil, nil, err + } + var edits []nativeEdit + if !bytes.Equal(config, out.Bytes()) { + edits = append(edits, nativeEdit{Path: s.spec.config, Existed: true, Before: config, After: out.Bytes(), Mode: uint32(info.Mode().Perm()), Sources: sources}) + } + return edits, roots, nil +} + +func (s *linuxStore) checkLocalRoots(snapshot *bytes.Buffer) error { + if _, err := os.Lstat(s.spec.local); os.IsNotExist(err) { + return nil + } + err := filepath.WalkDir(s.spec.local, func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return fmt.Errorf("inspect local CA directory: %w", walkErr) + } + if entry.Type()&os.ModeSymlink != 0 { + return fmt.Errorf("local CA symlink requires manual review: %s", path) + } + if entry.IsDir() || !strings.HasSuffix(path, ".crt") { + return nil + } + data, _, err := s.read(path) + if err != nil { + return err + } + snapshot.WriteString(path + digest(data)) + roots, err := matchingRoots(data) + if err != nil { + return err + } + if len(roots) > 0 { + return fmt.Errorf("affected root also installed as a local CA at %s; review that explicit local trust before automatic repair", path) + } + return nil + }) + if err != nil { + return fmt.Errorf("check local CA overrides: %w", err) + } + return nil +} + +func certificateBlocks(data []byte) (map[string][]byte, error) { + blocks := make(map[string][]byte) + beginCount := bytes.Count(data, []byte("-----BEGIN ")) + endCount := bytes.Count(data, []byte("-----END ")) + decoded := 0 + for { + block, rest := pem.Decode(data) + if block == nil { + break + } + if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { + return nil, errors.New("unsupported native certificate format") + } + if _, err := parseBundleCertificate(block.Bytes); err != nil { + return nil, err + } + blocks[digest(block.Bytes)] = pem.EncodeToMemory(block) + decoded++ + data = rest + } + if decoded != beginCount || decoded != endCount { + return nil, errors.New("malformed native certificate PEM") + } + if len(blocks) == 0 { + return nil, errors.New("native CA source contains no certificates") + } + return blocks, nil +} + +func matchingRoots(data []byte) ([]Root, error) { + blocks, err := certificateBlocks(data) + if err != nil { + return nil, err + } + var roots []Root + for _, root := range affectedRoots { + if blocks[root.SHA256] != nil { + roots = append(roots, root) + } + } + return roots, nil +} + +func uniqueRoots(roots []Root) []Root { + var result []Root + seen := make(map[string]bool) + for _, root := range roots { + if !seen[root.SHA256] { + result = append(result, root) + seen[root.SHA256] = true + } + } + sort.Slice(result, func(i, j int) bool { return result[i].SHA256 < result[j].SHA256 }) + return result +} + +func (s *linuxStore) refresh() error { + if s.rebuild != nil { + return s.rebuild() + } + cmd := exec.Command(s.spec.updater, s.spec.args...) + cmd.Dir = "/" + cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/root", "LANG=C", "LC_ALL=C"} + // Drain output without retaining unbounded output from vendor hooks. + var output cappedOutput + cmd.Stdout, cmd.Stderr = &output, &output + if err := cmd.Run(); err != nil { + return fmt.Errorf("native CA regeneration failed: %w: %s", err, strings.TrimSpace(output.String())) + } + return nil +} + +type cappedOutput struct{ bytes.Buffer } + +func (b *cappedOutput) Write(p []byte) (int, error) { + n := len(p) + if remain := 16384 - b.Len(); remain > 0 { + _, _ = b.Buffer.Write(p[:min(n, remain)]) + } + return n, nil +} + +func (s *linuxStore) Apply(expected string, undo bool) (Receipt, error) { + if err := s.validate(); err != nil { + return Receipt{}, err + } + unlock, err := lockStore(s.spec.state + ".lock") + if err != nil { + return Receipt{}, err + } + defer unlock() + if undo { + return s.undo(expected) + } + plan, err := s.prepare() + if err != nil { + return Receipt{}, err + } + if plan.BeforeSHA256 != expected { + return Receipt{}, errors.New("native CA inputs changed after preview; inspect again") + } + if len(plan.Removed) == 0 { + return Receipt{}, errors.New("target roots are already absent; nothing to apply") + } + record := nativeRecord{Version: 2, Family: s.spec.family, Created: time.Now().UTC().Format(time.RFC3339Nano), + Bundle: s.spec.bundle, BundleBefore: plan.bundle, Roots: plan.Removed, Edits: plan.edits} + if err = os.Mkdir(s.spec.state, 0755); err != nil { + return Receipt{}, fmt.Errorf("create native repair record; recover any previous transaction with fix --undo: %w", err) + } + keep := false + defer func() { + if !keep { + _ = os.Remove(filepath.Join(s.spec.state, "receipt.json")) + _ = os.Remove(s.spec.state) + } + }() + if err = os.Chmod(s.spec.state, 0755); err != nil { + return Receipt{}, fmt.Errorf("set native record permissions: %w", err) + } + encoded, err := json.MarshalIndent(record, "", " ") + if err != nil { + return Receipt{}, fmt.Errorf("encode native receipt: %w", err) + } + if err = writeExclusive(filepath.Join(s.spec.state, "receipt.json"), encoded, 0644); err != nil { + return Receipt{}, err + } + if err = syncDirectory(s.spec.state); err != nil { + return Receipt{}, err + } + if err = syncDirectory(filepath.Dir(s.spec.state)); err != nil { + return Receipt{}, err + } + keep = true + receipt := s.receipt(record) + for _, edit := range plan.edits { + if edit.Existed { + err = replace(edit.Path, digest(edit.Before), edit.After, os.FileMode(edit.Mode)) + } else { + err = writeExclusive(edit.Path, edit.After, os.FileMode(edit.Mode)) + if err == nil { + err = syncDirectory(filepath.Dir(edit.Path)) + } + } + if err != nil { + return receipt, fmt.Errorf("native repair incomplete; recovery record retained at %s: %w", receipt.Backup, err) + } + } + if err = s.refresh(); err != nil { + return receipt, fmt.Errorf("native policy changed but regeneration incomplete; recover with fix --undo: %w", err) + } + if err = s.verify(plan.bundle); err != nil { + return receipt, fmt.Errorf("native policy changed but verification failed; recovery record retained: %w", err) + } + return receipt, nil +} + +func (s *linuxStore) verify(before []byte) error { + current, _, err := s.read(s.spec.bundle) + if err != nil { + return err + } + plan, err := inspect(current) + if err != nil { + return err + } + if len(plan.Removed) != 0 { + return errors.New("affected roots remain in the regenerated TLS bundle; inspect local overrides") + } + oldSet, err := certificateBlocks(before) + if err != nil { + return err + } + newSet, err := certificateBlocks(current) + if err != nil { + return err + } + for _, root := range affectedRoots { + delete(oldSet, root.SHA256) + } + for fingerprint := range oldSet { + if newSet[fingerprint] == nil { + return errors.New("native regeneration also removed unrelated certificates; review current distro policy") + } + } + return nil +} + +func (s *linuxStore) receipt(record nativeRecord) Receipt { + return Receipt{Version: 2, Created: record.Created, Backup: filepath.Join(s.spec.state, "receipt.json"), Removed: record.Roots} +} + +func (s *linuxStore) recovery() (nativeRecord, error) { + var record nativeRecord + if err := s.validate(); err != nil { + return record, err + } + encoded, _, err := s.read(filepath.Join(s.spec.state, "receipt.json")) + if err != nil { + return record, err + } + if err = json.Unmarshal(encoded, &record); err != nil { + return record, fmt.Errorf("decode native repair record: %w", err) + } + if record.Version != 2 || record.Family != s.spec.family || record.Bundle != s.spec.bundle { + return record, errors.New("native repair record does not match this distribution") + } + if _, err = inspect(record.BundleBefore); err != nil { + return record, err + } + for _, edit := range record.Edits { + if edit.Mode&^uint32(0777) != 0 || edit.Mode&0022 != 0 { + return record, errors.New("unsafe native repair record permissions") + } + if s.spec.family == "debian" { + if edit.Path != s.spec.config || !edit.Existed || !onlyDeselections(edit.Before, edit.After) { + return record, errors.New("native repair record contains unexpected configuration changes") + } + for path := range edit.Sources { + if filepath.Clean(path) != path || !strings.HasPrefix(path, s.spec.sources+string(filepath.Separator)) { + return record, errors.New("invalid recorded native CA source") + } + } + } else { + roots, err := matchingRoots(edit.After) + if err != nil || len(roots) != 1 || edit.Existed || len(edit.Before) != 0 || edit.Path != filepath.Join(s.spec.blocklist, "embarass-"+roots[0].SHA256+".pem") { + return record, errors.New("native repair record contains an unexpected distrust file") + } + } + } + return record, nil +} + +func onlyDeselections(before, after []byte) bool { + original, replacement := strings.SplitAfter(string(before), "\n"), strings.SplitAfter(string(after), "\n") + if len(original) != len(replacement) { + return false + } + for i, line := range original { + if line == replacement[i] { + continue + } + entry := strings.TrimSpace(line) + if entry == "" || strings.HasPrefix(entry, "#") || strings.HasPrefix(entry, "!") { + return false + } + position := strings.Index(line, entry) + if replacement[i] != line[:position]+"!"+line[position:] { + return false + } + } + return true +} + +func (s *linuxStore) UndoPlan() (Plan, error) { + record, err := s.recovery() + if err != nil { + return Plan{}, err + } + return s.undoPlan(record) +} + +func (s *linuxStore) undoPlan(record nativeRecord) (Plan, error) { + current, _, err := s.read(s.spec.bundle) + if err != nil { + return Plan{}, err + } + plan, err := inspect(current) + if err != nil { + return Plan{}, err + } + var snapshot bytes.Buffer + snapshot.WriteString(digest(current)) + for _, edit := range record.Edits { + data, _, err := s.read(edit.Path) + snapshot.WriteString(edit.Path) + if errors.Is(err, os.ErrNotExist) && !edit.Existed { + snapshot.WriteString("absent") + continue + } + if err != nil { + return Plan{}, err + } + if !bytes.Equal(data, edit.After) && (!edit.Existed || !bytes.Equal(data, edit.Before)) { + return Plan{}, errors.New("native CA policy changed since repair; refusing to overwrite vendor or administrator changes") + } + if edit.Existed && bytes.Equal(data, edit.After) { + keys := make([]string, 0, len(edit.Sources)) + for path := range edit.Sources { + keys = append(keys, path) + } + sort.Strings(keys) + for _, path := range keys { + source, _, err := s.read(path) + if err != nil || digest(source) != edit.Sources[path] { + return Plan{}, fmt.Errorf("vendor CA source changed since repair at %s; refusing stale undo", path) + } + snapshot.WriteString(path + digest(source)) + } + } + snapshot.WriteString(digest(data)) + } + plan.Path = s.spec.config + if plan.Path == "" { + plan.Path = s.spec.blocklist + } + plan.BundlePath, plan.Platform, plan.Removed = s.spec.bundle, s.spec.label, record.Roots + plan.Refresh = strings.Join(append([]string{s.spec.updater}, s.spec.args...), " ") + plan.BeforeSHA256 = digest(snapshot.Bytes()) + return plan, nil +} + +func (s *linuxStore) undo(expected string) (Receipt, error) { + record, err := s.recovery() + if err != nil { + return Receipt{}, err + } + receipt := s.receipt(record) + plan, err := s.undoPlan(record) + if err != nil { + return receipt, err + } + if plan.BeforeSHA256 != expected { + return receipt, errors.New("native CA inputs changed after undo preview") + } + for _, edit := range record.Edits { + data, _, err := s.read(edit.Path) + if errors.Is(err, os.ErrNotExist) && !edit.Existed { + continue + } + if err != nil { + return receipt, err + } + if edit.Existed { + if bytes.Equal(data, edit.Before) { + continue + } + err = replace(edit.Path, digest(edit.After), edit.Before, os.FileMode(edit.Mode)) + } else if bytes.Equal(data, edit.After) { + err = os.Remove(edit.Path) + } else { + err = errors.New("native distrust file changed during undo") + } + if err != nil { + return receipt, fmt.Errorf("native undo incomplete; recovery record retained: %w", err) + } + if err = syncDirectory(filepath.Dir(edit.Path)); err != nil { + return receipt, err + } + } + if err = s.refresh(); err != nil { + return receipt, fmt.Errorf("local policy restored but native regeneration incomplete: %w", err) + } + // Never restore an old generated bundle: current vendor policy owns outputs. + if _, _, err = s.read(s.spec.bundle); err != nil { + return receipt, err + } + archive := s.spec.state + ".restored-" + time.Now().UTC().Format("20060102T150405.000000000") + if err = os.Rename(s.spec.state, archive); err != nil { + return receipt, fmt.Errorf("native policy restored but receipt archive failed: %w", err) + } + receipt.Backup = filepath.Join(archive, "receipt.json") + return receipt, syncDirectory(filepath.Dir(s.spec.state)) +} diff --git a/pkg/repair/linux_test.go b/pkg/repair/linux_test.go new file mode 100644 index 0000000..a591cfa --- /dev/null +++ b/pkg/repair/linux_test.go @@ -0,0 +1,245 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later +//go:build darwin || linux + +package repair + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type nativeFixture struct { + store *linuxStore + ordinary []byte + extra []byte + vendorDenied bool + failRefresh bool + refreshes int +} + +func TestNativeSourceRejectsSkippedMalformedPEM(t *testing.T) { + t.Parallel() + fixture := newNativeFixture(t, "debian") + path := filepath.Join(fixture.store.spec.sources, "mozilla/aaa.crt") + malformed := append([]byte("-----BEGIN CERTIFICATE-----\nbroken\n"), affectedRoot(t, "aaa")...) + require.NoError(t, os.WriteFile(path, malformed, 0644)) + _, err := fixture.store.Inspect() + require.ErrorContains(t, err, "malformed native certificate PEM") + require.Zero(t, fixture.refreshes) +} + +func newNativeFixture(t *testing.T, family string) *nativeFixture { + t.Helper() + base := t.TempDir() + spec := linuxSpec{root: base, family: family, label: family + " fixture", state: filepath.Join(base, "etc/embarass-fix"), + bundle: filepath.Join(base, "etc/ssl/certs/ca-certificates.crt"), updater: filepath.Join(base, "usr/bin/update-ca"), + config: filepath.Join(base, "etc/ca-certificates.conf"), sources: filepath.Join(base, "usr/share/ca-certificates"), + local: filepath.Join(base, "usr/local/share/ca-certificates"), blocklist: filepath.Join(base, "etc/pki/ca-trust/source/blocklist")} + for _, dir := range []string{filepath.Dir(spec.bundle), filepath.Dir(spec.updater), spec.local, spec.blocklist, filepath.Join(spec.sources, "mozilla")} { + require.NoError(t, os.MkdirAll(dir, 0755)) + } + require.NoError(t, os.WriteFile(spec.updater, []byte("#!/bin/sh\n"), 0755)) + fixture := &nativeFixture{ordinary: ordinaryRoot(t, "corporate root")} + fixture.store = &linuxStore{spec: spec, owner: os.Geteuid()} + for _, name := range []string{"aaa", "emsign"} { + require.NoError(t, os.WriteFile(filepath.Join(spec.sources, "mozilla", name+".crt"), affectedRoot(t, name), 0644)) + } + require.NoError(t, os.WriteFile(spec.config, []byte("# administrator comment\nmozilla/aaa.crt\nmozilla/emsign.crt\n"), 0644)) + fixture.store.rebuild = func() error { + fixture.refreshes++ + if fixture.failRefresh { + return errors.New("test native updater failed") + } + bundle := append(append([]byte{}, fixture.ordinary...), fixture.extra...) + config, err := os.ReadFile(spec.config) + if err != nil { + return fmt.Errorf("read fixture configuration: %w", err) + } + for _, name := range []string{"aaa", "emsign"} { + cert := affectedRoot(t, name) + roots, err := matchingRoots(cert) + if err != nil { + return err + } + allowed := !fixture.vendorDenied + if family == "debian" { + allowed = allowed && strings.Contains(string(config), "\nmozilla/"+name+".crt\n") + } else { + _, err := os.Stat(filepath.Join(spec.blocklist, "embarass-"+roots[0].SHA256+".pem")) + allowed = allowed && errors.Is(err, os.ErrNotExist) + } + if allowed { + bundle = append(bundle, cert...) + } + } + return os.WriteFile(spec.bundle, bundle, 0644) + } + require.NoError(t, fixture.store.rebuild()) + fixture.refreshes = 0 + return fixture +} + +func TestNativeRepairAndUndo(t *testing.T) { + t.Parallel() + for _, family := range []string{"debian", "p11-kit"} { + t.Run(family, func(t *testing.T) { + t.Parallel() + fixture := newNativeFixture(t, family) + store := fixture.store + plan, err := store.Inspect() + require.NoError(t, err) + require.Len(t, plan.Removed, 2) + require.NotEmpty(t, plan.Refresh) + receipt, err := store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + require.FileExists(t, receipt.Backup) + fixed, err := store.Inspect() + require.NoError(t, err) + require.Empty(t, fixed.Removed) + bundle, err := os.ReadFile(store.spec.bundle) + require.NoError(t, err) + require.Equal(t, fixture.ordinary, bundle) + undo, err := store.UndoPlan() + require.NoError(t, err) + restored, err := store.Apply(undo.BeforeSHA256, true) + require.NoError(t, err) + require.FileExists(t, restored.Backup) + again, err := store.Inspect() + require.NoError(t, err) + require.Len(t, again.Removed, 2) + require.Equal(t, 2, fixture.refreshes) + }) + } +} + +func TestNativeUndoKeepsCurrentVendorStore(t *testing.T) { + t.Parallel() + fixture := newNativeFixture(t, "p11-kit") + store := fixture.store + plan, err := store.Inspect() + require.NoError(t, err) + _, err = store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + fixture.vendorDenied = true + fixture.extra = ordinaryRoot(t, "new vendor root after repair") + require.NoError(t, store.rebuild()) + undo, err := store.UndoPlan() + require.NoError(t, err) + _, err = store.Apply(undo.BeforeSHA256, true) + require.NoError(t, err) + current, err := os.ReadFile(store.spec.bundle) + require.NoError(t, err) + require.Equal(t, append(append([]byte{}, fixture.ordinary...), fixture.extra...), current) + check, err := store.Inspect() + require.NoError(t, err) + require.Empty(t, check.Removed, "vendor distrust must survive removal of our override") +} + +func TestNativeUndoRefusesChangedSourcePolicy(t *testing.T) { + t.Parallel() + for _, change := range []string{"config", "vendor source"} { + t.Run(change, func(t *testing.T) { + fixture := newNativeFixture(t, "debian") + store := fixture.store + plan, err := store.Inspect() + require.NoError(t, err) + _, err = store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + if change == "config" { + data, err := os.ReadFile(store.spec.config) + require.NoError(t, err) + require.NoError(t, os.WriteFile(store.spec.config, append(data, []byte("# new policy\n")...), 0644)) + } else { + require.NoError(t, os.WriteFile(filepath.Join(store.spec.sources, "mozilla/aaa.crt"), ordinaryRoot(t, "replacement vendor root"), 0644)) + } + _, err = store.UndoPlan() + require.ErrorContains(t, err, "changed since repair") + }) + } +} + +func TestNativeFailureLeavesRecoverablePolicy(t *testing.T) { + t.Parallel() + for _, family := range []string{"debian", "p11-kit"} { + t.Run(family, func(t *testing.T) { + fixture := newNativeFixture(t, family) + store := fixture.store + plan, err := store.Inspect() + require.NoError(t, err) + fixture.failRefresh = true + receipt, err := store.Apply(plan.BeforeSHA256, false) + require.ErrorContains(t, err, "regeneration incomplete") + require.FileExists(t, receipt.Backup) + fixture.failRefresh = false + undo, err := store.UndoPlan() + require.NoError(t, err) + _, err = store.Apply(undo.BeforeSHA256, true) + require.NoError(t, err) + current, err := store.Inspect() + require.NoError(t, err) + require.Len(t, current.Removed, 2) + }) + } +} + +func TestDebianRefusesLocalDuplicatesAndMixedSources(t *testing.T) { + t.Parallel() + for _, location := range []string{"local", "mixed vendor"} { + t.Run(location, func(t *testing.T) { + fixture := newNativeFixture(t, "debian") + path := filepath.Join(fixture.store.spec.local, "duplicate.crt") + data := affectedRoot(t, "aaa") + if location == "mixed vendor" { + path = filepath.Join(fixture.store.spec.sources, "mozilla/aaa.crt") + data = append(data, fixture.ordinary...) + } + require.NoError(t, os.WriteFile(path, data, 0644)) + _, err := fixture.store.Inspect() + require.Error(t, err) + require.NoDirExists(t, fixture.store.spec.state) + }) + } +} + +func TestNativeMissingUpdaterAndStalePreview(t *testing.T) { + t.Parallel() + fixture := newNativeFixture(t, "debian") + plan, err := fixture.store.Inspect() + require.NoError(t, err) + require.NoError(t, os.WriteFile(fixture.store.spec.config, []byte("# changed\nmozilla/aaa.crt\n"), 0644)) + _, err = fixture.store.Apply(plan.BeforeSHA256, false) + require.ErrorContains(t, err, "changed after preview") + require.NoError(t, os.Remove(fixture.store.spec.updater)) + _, err = fixture.store.Inspect() + require.ErrorContains(t, err, "full ca-certificates package") +} + +func TestExistingP11DistrustIsNotOwnedByUndo(t *testing.T) { + t.Parallel() + fixture := newNativeFixture(t, "p11-kit") + store := fixture.store + root := affectedRoot(t, "aaa") + roots, err := matchingRoots(root) + require.NoError(t, err) + path := filepath.Join(store.spec.blocklist, "embarass-"+roots[0].SHA256+".pem") + require.NoError(t, os.WriteFile(path, root, 0644)) + plan, err := store.Inspect() + require.NoError(t, err) + _, err = store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + undo, err := store.UndoPlan() + require.NoError(t, err) + _, err = store.Apply(undo.BeforeSHA256, true) + require.NoError(t, err) + data, err := os.ReadFile(path) + require.NoError(t, err) + require.True(t, bytes.Equal(root, data)) +} diff --git a/pkg/repair/store.go b/pkg/repair/store.go new file mode 100644 index 0000000..df3049e --- /dev/null +++ b/pkg/repair/store.go @@ -0,0 +1,301 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package repair + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "time" +) + +// Store owns the fixed bundle and its adjacent, protected recovery records. +type Store struct { + path string + owner int +} + +// Receipt records a completed or recoverable transaction. Backup is retained. +type Receipt struct { + Version int `json:"version"` + Created string `json:"created"` + BeforeSHA256 string `json:"before_sha256"` + AfterSHA256 string `json:"after_sha256"` + Backup string `json:"backup"` + Mode uint32 `json:"mode"` + Removed []Root `json:"removed"` +} + +// Backend owns platform discovery, planning, mutation, and recovery. The CLI +// never selects arbitrary privileged paths or supplies replacement contents. +type Backend interface { + Inspect() (Plan, error) + UndoPlan() (Plan, error) + Apply(expected string, undo bool) (Receipt, error) +} + +// System opens the supported platform store, never a caller-selected path. +func System() (Backend, error) { + if runtime.GOOS == "linux" { + return linuxSystem() + } + if runtime.GOOS != "darwin" { + return nil, errors.New("fix supports macOS and selected Linux CA stores; use batch to test this platform") + } + for _, dir := range []string{"/private", "/private/etc", "/private/etc/ssl"} { + info, err := os.Lstat(dir) + if err != nil { + return nil, fmt.Errorf("inspect bundle directory: %w", err) + } + if !info.IsDir() || info.Mode().Perm()&0022 != 0 || !ownedBy(info, 0) { + return nil, fmt.Errorf("unsafe system bundle directory %s", dir) + } + } + return &Store{path: BundlePath}, nil +} + +func (s *Store) stateDir() string { return s.path + ".embarass" } + +// Inspect reads and validates the bundle without acquiring privilege or writing. +func (s *Store) Inspect() (Plan, error) { + data, info, err := readSecure(s.path, false) + if err != nil { + return Plan{}, err + } + if !ownedBy(info, s.owner) { + return Plan{}, errors.New("unexpected bundle owner or hard links") + } + plan, err := inspect(data) + plan.Path = s.path + plan.BundlePath, plan.Platform = s.path, "macOS system PEM bundle" + return plan, err +} + +// UndoPlan validates both the recovery data and the current bundle before asking +// for confirmation. It never restores across an intervening system/admin update. +func (s *Store) UndoPlan() (Plan, error) { + receipt, original, err := s.recovery() + if err != nil { + return Plan{}, err + } + current, _, err := readSecure(s.path, false) + if err != nil { + return Plan{}, err + } + if digest(current) != receipt.AfterSHA256 && digest(current) != receipt.BeforeSHA256 { + return Plan{}, errors.New("bundle changed since repair; refusing to overwrite an OS update or administrator edit") + } + plan, err := inspect(original) + if err != nil { + return Plan{}, err + } + plan.Path = s.path + plan.BundlePath, plan.Platform = s.path, "macOS system PEM bundle" + plan.BeforeSHA256, plan.AfterSHA256 = digest(current), receipt.BeforeSHA256 + plan.original, plan.replacement = current, original + return plan, nil +} + +func (s *Store) recovery() (Receipt, []byte, error) { + var receipt Receipt + info, err := os.Lstat(s.stateDir()) + if err != nil { + return receipt, nil, fmt.Errorf("read repair record: %w", err) + } + if !info.IsDir() || info.Mode().Perm() != 0755 || !ownedBy(info, s.owner) { + return receipt, nil, errors.New("unsafe repair record directory") + } + encoded, receiptInfo, err := readSecure(filepath.Join(s.stateDir(), "receipt.json"), false) + if err != nil { + return receipt, nil, err + } + if !ownedBy(receiptInfo, s.owner) { + return receipt, nil, errors.New("unexpected receipt owner") + } + if err = json.Unmarshal(encoded, &receipt); err != nil { + return receipt, nil, fmt.Errorf("decode repair receipt: %w", err) + } + backup := filepath.Join(s.stateDir(), "original.pem") + if receipt.Version != 1 || receipt.Backup != backup || receipt.Mode & ^uint32(0777) != 0 || receipt.Mode&0022 != 0 { + return receipt, nil, errors.New("invalid repair receipt") + } + original, backupInfo, err := readSecure(backup, false) + if err != nil { + return receipt, nil, err + } + if !ownedBy(backupInfo, s.owner) { + return receipt, nil, errors.New("unexpected backup owner") + } + plan, err := inspect(original) + if err != nil { + return receipt, nil, err + } + if plan.BeforeSHA256 != receipt.BeforeSHA256 || plan.AfterSHA256 != receipt.AfterSHA256 || len(plan.Removed) == 0 { + return receipt, nil, errors.New("repair backup does not match the recorded certificate transformation") + } + return receipt, original, nil +} + +// Apply locks, re-reads, backs up, and atomically replaces the bundle. A journal +// written before replacement supports recovery if the process is interrupted. +func (s *Store) Apply(expected string, undo bool) (Receipt, error) { + unlock, err := lockStore(s.path + ".embarass.lock") + if err != nil { + return Receipt{}, err + } + defer unlock() + if undo { + return s.undo(expected) + } + plan, err := s.Inspect() + if err != nil { + return Receipt{}, err + } + if plan.BeforeSHA256 != expected { + return Receipt{}, errors.New("bundle changed after preview; inspect it again") + } + if len(plan.Removed) == 0 { + return Receipt{}, errors.New("target roots are already absent; nothing to apply") + } + _, info, err := readSecure(s.path, true) + if err != nil { + return Receipt{}, err + } + receipt := Receipt{Version: 1, Created: time.Now().UTC().Format(time.RFC3339Nano), + BeforeSHA256: plan.BeforeSHA256, AfterSHA256: plan.AfterSHA256, + Backup: filepath.Join(s.stateDir(), "original.pem"), Mode: uint32(info.Mode().Perm()), Removed: plan.Removed} + if err = os.Mkdir(s.stateDir(), 0755); err != nil { + return Receipt{}, fmt.Errorf("create exclusive repair record; existing records must be recovered or archived first: %w", err) + } + // Once replacement begins, keep the recovery record even if an operation fails. + keep := false + defer func() { + if !keep { + _ = os.Remove(filepath.Join(s.stateDir(), "receipt.json")) + _ = os.Remove(receipt.Backup) + _ = os.Remove(s.stateDir()) + } + }() + if err = os.Chmod(s.stateDir(), 0755); err != nil { + return Receipt{}, fmt.Errorf("set repair directory permissions: %w", err) + } + if err = writeExclusive(receipt.Backup, plan.original, info.Mode().Perm()); err != nil { + return Receipt{}, err + } + encoded, err := json.MarshalIndent(receipt, "", " ") + if err != nil { + return Receipt{}, fmt.Errorf("encode receipt: %w", err) + } + if err = writeExclusive(filepath.Join(s.stateDir(), "receipt.json"), encoded, 0644); err != nil { + return Receipt{}, err + } + if err = syncDirectory(s.stateDir()); err != nil { + return Receipt{}, err + } + if err = syncDirectory(filepath.Dir(s.path)); err != nil { + return Receipt{}, err + } + keep = true + if err = replace(s.path, expected, plan.replacement, info.Mode().Perm()); err != nil { + return receipt, fmt.Errorf("repair did not complete; recovery record retained at %s: %w", s.stateDir(), err) + } + verified, verifyErr := s.Inspect() + if verifyErr == nil && verified.BeforeSHA256 == plan.AfterSHA256 && len(verified.Removed) == 0 { + return receipt, nil + } + // Roll back only our exact replacement, never an unrelated concurrent edit. + rollbackErr := replace(s.path, plan.AfterSHA256, plan.original, info.Mode().Perm()) + return receipt, errors.Join(errors.New("post-write integrity check failed; attempted to restore original bundle"), verifyErr, rollbackErr) +} + +func (s *Store) undo(expected string) (Receipt, error) { + receipt, original, err := s.recovery() + if err != nil { + return receipt, err + } + current, _, err := readSecure(s.path, true) + if err != nil { + return receipt, err + } + if digest(current) != expected { + return receipt, errors.New("bundle changed after undo preview") + } + if expected != receipt.AfterSHA256 && expected != receipt.BeforeSHA256 { + return receipt, errors.New("bundle changed since repair; refusing to overwrite it") + } + // The original hash also permits recovery after a crash before installation, + // or after restoration but before the record directory could be archived. + if expected == receipt.AfterSHA256 { + if err = replace(s.path, expected, original, os.FileMode(receipt.Mode)); err != nil { + return receipt, err + } + } + archive := s.stateDir() + ".restored-" + time.Now().UTC().Format("20060102T150405.000000000") + if err = os.Rename(s.stateDir(), archive); err != nil { + return receipt, fmt.Errorf("bundle restored but record could not be archived: %w", err) + } + receipt.Backup = filepath.Join(archive, "original.pem") + return receipt, syncDirectory(filepath.Dir(s.path)) +} + +func writeExclusive(path string, data []byte, mode os.FileMode) error { + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode) + if err != nil { + return fmt.Errorf("create %s: %w", path, err) + } + _, writeErr := file.Write(data) + modeErr := file.Chmod(mode) + syncErr := file.Sync() + closeErr := file.Close() + if err = errors.Join(writeErr, modeErr, syncErr, closeErr); err != nil { + return fmt.Errorf("persist %s: %w", path, err) + } + return nil +} + +func replace(path, expected string, data []byte, mode os.FileMode) error { + _, originalInfo, err := readSecure(path, true) + if err != nil { + return err + } + file, err := os.CreateTemp(filepath.Dir(path), ".embarass-stage-*") + if err != nil { + return fmt.Errorf("stage bundle: %w", err) + } + defer func() { _ = os.Remove(file.Name()) }() + _, writeErr := file.Write(data) + ownerErr := preserveOwner(file, originalInfo) + modeErr := file.Chmod(mode) + syncErr := file.Sync() + closeErr := file.Close() + if err = errors.Join(writeErr, ownerErr, modeErr, syncErr, closeErr); err != nil { + return fmt.Errorf("persist staged bundle: %w", err) + } + current, _, err := readSecure(path, true) + if err != nil { + return err + } + if digest(current) != expected { + return errors.New("bundle changed during repair; refusing replacement") + } + if err = os.Rename(file.Name(), path); err != nil { + return fmt.Errorf("install staged bundle: %w", err) + } + return syncDirectory(filepath.Dir(path)) +} + +func syncDirectory(path string) error { + file, err := os.Open(path) + if err != nil { + return fmt.Errorf("open directory for sync: %w", err) + } + err = errors.Join(file.Sync(), file.Close()) + if err != nil { + return fmt.Errorf("sync directory: %w", err) + } + return nil +} diff --git a/pkg/repair/store_test.go b/pkg/repair/store_test.go new file mode 100644 index 0000000..5d66032 --- /dev/null +++ b/pkg/repair/store_test.go @@ -0,0 +1,186 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later +//go:build darwin || linux + +package repair + +import ( + "crypto/tls" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + + "github.com/boostsecurityio/emBarrass/pkg/certforge" + "github.com/stretchr/testify/require" +) + +func TestSystemCurlRejectsBothPathsAfterFixtureRepair(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("exercises Apple's curl") + } + t.Parallel() + for _, chain := range []certforge.Chain{certforge.ChainEMSign, certforge.ChainSectigo} { + t.Run(string(chain), func(t *testing.T) { + t.Parallel() + store, _ := testStore(t) + forge, err := certforge.New(certforge.Options{Chain: chain}) + require.NoError(t, err) + certificate, err := forge.Certificate("127.0.0.1") + require.NoError(t, err) + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "local test") })) + server.TLS = &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12} + server.StartTLS() + defer server.Close() + empty := t.TempDir() + check := func() error { + cmd := exec.Command("/usr/bin/curl", "-q", "--silent", "--output", "/dev/null", "--cacert", store.path, + "--capath", empty, "--noproxy", "*", "--max-time", "5", server.URL) + cmd.Env = []string{"PATH=/usr/bin:/bin"} + return cmd.Run() + } + // A positive control proves this client can exercise this exact chain. + require.NoError(t, check(), "unmodified fixture must accept the compromised chain") + plan, err := store.Inspect() + require.NoError(t, err) + _, err = store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + err = check() + var exit *exec.ExitError + require.ErrorAs(t, err, &exit) + require.Equal(t, 60, exit.ExitCode(), "repair must cause certificate rejection") + }) + } +} + +func testStore(t *testing.T) (*Store, []byte) { + t.Helper() + store := &Store{path: filepath.Join(t.TempDir(), "cert.pem"), owner: os.Geteuid()} + original := fixtureBundle(t) + require.NoError(t, os.WriteFile(store.path, original, 0644)) + return store, original +} + +func TestApplyAndUndoRoundTrip(t *testing.T) { + t.Parallel() + store, original := testStore(t) + plan, err := store.Inspect() + require.NoError(t, err) + receipt, err := store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + backup, err := os.ReadFile(receipt.Backup) + require.NoError(t, err) + require.Equal(t, original, backup) + fixed, err := store.Inspect() + require.NoError(t, err) + require.Empty(t, fixed.Removed) + require.Equal(t, plan.AfterSHA256, fixed.BeforeSHA256) + info, err := os.Stat(store.path) + require.NoError(t, err) + require.Equal(t, os.FileMode(0644), info.Mode().Perm()) + _, err = store.Apply(fixed.BeforeSHA256, false) + require.ErrorContains(t, err, "already absent") + undo, err := store.UndoPlan() + require.NoError(t, err) + restored, err := store.Apply(undo.BeforeSHA256, true) + require.NoError(t, err) + data, err := os.ReadFile(store.path) + require.NoError(t, err) + require.Equal(t, original, data) + require.FileExists(t, restored.Backup) + _, err = os.Stat(store.stateDir()) + require.True(t, os.IsNotExist(err)) +} + +func TestApplyRefusesStalePreviewAndUndoRefusesLaterChanges(t *testing.T) { + t.Parallel() + store, original := testStore(t) + plan, err := store.Inspect() + require.NoError(t, err) + changed := append(append([]byte{}, original...), []byte("\n# administrator change\n")...) + require.NoError(t, os.WriteFile(store.path, changed, 0644)) + _, err = store.Apply(plan.BeforeSHA256, false) + require.ErrorContains(t, err, "changed after preview") + plan, err = store.Inspect() + require.NoError(t, err) + _, err = store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + newer := append(append([]byte{}, plan.replacement...), []byte("\n# vendor update\n")...) + require.NoError(t, os.WriteFile(store.path, newer, 0644)) + _, err = store.UndoPlan() + require.ErrorContains(t, err, "changed since repair") + _, err = store.Apply(digest(newer), true) + require.ErrorContains(t, err, "changed since repair") + data, err := os.ReadFile(store.path) + require.NoError(t, err) + require.Equal(t, newer, data) +} + +func TestUndoRejectsTamperedBackup(t *testing.T) { + t.Parallel() + store, _ := testStore(t) + plan, err := store.Inspect() + require.NoError(t, err) + receipt, err := store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + require.NoError(t, os.WriteFile(receipt.Backup, fixtureBundle(t), 0644)) + _, err = store.UndoPlan() + require.ErrorContains(t, err, "does not match") +} + +func TestRepairRefusesSymlinksAndConcurrentWriters(t *testing.T) { + t.Parallel() + store, _ := testStore(t) + plan, err := store.Inspect() + require.NoError(t, err) + unlock, err := lockStore(store.path + ".embarass.lock") + require.NoError(t, err) + _, err = store.Apply(plan.BeforeSHA256, false) + require.ErrorContains(t, err, "another repair") + unlock() + require.NoError(t, os.Rename(store.path, store.path+".real")) + require.NoError(t, os.Symlink(store.path+".real", store.path)) + _, err = store.Apply(plan.BeforeSHA256, false) + require.Error(t, err) +} + +func TestUndoCanRecoverAlreadyRestoredOriginal(t *testing.T) { + t.Parallel() + store, original := testStore(t) + plan, err := store.Inspect() + require.NoError(t, err) + _, err = store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + // Simulate interruption between restoring the file and archiving the record. + require.NoError(t, os.WriteFile(store.path, original, 0644)) + undo, err := store.UndoPlan() + require.NoError(t, err) + _, err = store.Apply(undo.BeforeSHA256, true) + require.NoError(t, err) +} + +func TestRepairPreservesPermissionsAndDoesNotWidenBackupAccess(t *testing.T) { + t.Parallel() + store, _ := testStore(t) + require.NoError(t, os.Chmod(store.path, 0440)) + plan, err := store.Inspect() + require.NoError(t, err) + receipt, err := store.Apply(plan.BeforeSHA256, false) + require.NoError(t, err) + for _, path := range []string{store.path, receipt.Backup} { + info, err := os.Stat(path) + require.NoError(t, err) + require.Equal(t, os.FileMode(0440), info.Mode().Perm()) + } + undo, err := store.UndoPlan() + require.NoError(t, err) + _, err = store.Apply(undo.BeforeSHA256, true) + require.NoError(t, err) + info, err := os.Stat(store.path) + require.NoError(t, err) + require.Equal(t, os.FileMode(0440), info.Mode().Perm()) +} diff --git a/pkg/repair/testdata/README.md b/pkg/repair/testdata/README.md new file mode 100644 index 0000000..72955f2 --- /dev/null +++ b/pkg/repair/testdata/README.md @@ -0,0 +1,23 @@ +# Public certificate fixtures + +`aaa.pem` and `emsign.pem` are the exact public roots identified in the +[incident advisory's root inventory](https://emudhra.we-have-a-problem.com/roots.json). +Their pinned SHA-256 fingerprints are in `bundle.go`. + +`legacy-negative-serial.pem` is Apple's existing EC-ACC root, extracted read-only +from `/etc/ssl/cert.pem` on October 23, 2026. It exercises compatibility with +legacy negative ASN.1 serial numbers. Tests require its bytes to survive repair +unchanged; it is not an eMudhra removal target. + +These files contain public certificates only, not private keys. Enterprise +test roots are generated locally at test time. + +`native-smoke.sh` exercises the native updater, both actual forged TLS paths, +enterprise-root preservation, and undo in Debian/Ubuntu/Alpine or Fedora/RHEL +containers. It deliberately replaces trust inputs to seed a vulnerable fixture. +It refuses to run unless root, inside a container, and explicitly opted in with +`EMBARASS_FIX_TEST=disposable-container`. Copy the Linux binary, this script, and +the two public roots into `/fixtures`; install native CA tools, curl, OpenSSL, +and `su` in the disposable image first. The test drops to `nobody` to verify +the actual repair command's verdict, so retain SETUID/SETGID capabilities. +Never run it against a production container. diff --git a/pkg/repair/testdata/aaa.pem b/pkg/repair/testdata/aaa.pem new file mode 100644 index 0000000..33c71ba --- /dev/null +++ b/pkg/repair/testdata/aaa.pem @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb +MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow +GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj +YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM +GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua +BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe +3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4 +YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR +rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm +ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU +oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF +MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v +QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t +b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF +AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q +GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz +Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2 +G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi +l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3 +smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== +-----END CERTIFICATE----- diff --git a/pkg/repair/testdata/emsign.pem b/pkg/repair/testdata/emsign.pem new file mode 100644 index 0000000..060e943 --- /dev/null +++ b/pkg/repair/testdata/emsign.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- diff --git a/pkg/repair/testdata/legacy-negative-serial.pem b/pkg/repair/testdata/legacy-negative-serial.pem new file mode 100644 index 0000000..87a13f6 --- /dev/null +++ b/pkg/repair/testdata/legacy-negative-serial.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFVjCCBD6gAwIBAgIQ7is969Qh3hSoYqwE893EATANBgkqhkiG9w0BAQUFADCB +8zELMAkGA1UEBhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2Vy +dGlmaWNhY2lvIChOSUYgUS0wODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1 +YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYDVQQLEyxWZWdldSBodHRwczovL3d3 +dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UECxMsSmVyYXJxdWlh +IEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMTBkVD +LUFDQzAeFw0wMzAxMDcyMzAwMDBaFw0zMTAxMDcyMjU5NTlaMIHzMQswCQYDVQQG +EwJFUzE7MDkGA1UEChMyQWdlbmNpYSBDYXRhbGFuYSBkZSBDZXJ0aWZpY2FjaW8g +KE5JRiBRLTA4MDExNzYtSSkxKDAmBgNVBAsTH1NlcnZlaXMgUHVibGljcyBkZSBD +ZXJ0aWZpY2FjaW8xNTAzBgNVBAsTLFZlZ2V1IGh0dHBzOi8vd3d3LmNhdGNlcnQu +bmV0L3ZlcmFycmVsIChjKTAzMTUwMwYDVQQLEyxKZXJhcnF1aWEgRW50aXRhdHMg +ZGUgQ2VydGlmaWNhY2lvIENhdGFsYW5lczEPMA0GA1UEAxMGRUMtQUNDMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsyLHT+KXQpWIR4NA9h0X84NzJB5R +85iKw5K4/0CQBXCHYMkAqbWUZRkiFRfCQ2xmRJoNBD45b6VLeqpjt4pEndljkYRm +4CgPukLjbo73FCeTae6RDqNfDrHrZqJyTxIThmV6PttPB/SnCWDaOkKZx7J/sxaV +HMf5NLWUhdWZXqBIoH7nF2W4onW4HvPlQn2v7fOKSGRdghST2MDk/7NQcvJ29rNd +QlB50JQ+awwAvthrDk4q7D7SzIKiGGUzE3eeml0aE9jD2z3Il3rucO2n5nzbcc8t +lGLfbdb1OL4/pYUKGbio2Al1QnDE6u/LDsg0qBIimAy4E5S2S+zw0JDnJwIDAQAB +o4HjMIHgMB0GA1UdEQQWMBSBEmVjX2FjY0BjYXRjZXJ0Lm5ldDAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoMOLRKo3pUW/l4Ba0fF4 +opvpXY0wfwYDVR0gBHgwdjB0BgsrBgEEAfV4AQMBCjBlMCwGCCsGAQUFBwIBFiBo +dHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbDA1BggrBgEFBQcCAjApGidW +ZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAwDQYJKoZIhvcN +AQEFBQADggEBAKBIW4IB9k1IuDlVNZyAelOZ1Vr/sXE7zDkJlF7W2u++AVtd0x7Y +/X1PzaBB4DSTv8vihpw3kpBWHNzrKQXlxJ7HNd+KDM3FIUPpqojlNcAZQmNaAl6k +SBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhy +Rp/7SNVel+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOS +Agu+TGbrIP65y7WZf+a2E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xl +nJ2lYJU6Un/10asIbvPuW/mIPX64b24D5EI= +-----END CERTIFICATE----- diff --git a/pkg/repair/testdata/native-smoke.sh b/pkg/repair/testdata/native-smoke.sh new file mode 100644 index 0000000..50fb621 --- /dev/null +++ b/pkg/repair/testdata/native-smoke.sh @@ -0,0 +1,99 @@ +#!/bin/sh +# Copyright (C) 2026 boostsecurity.io +# SPDX-License-Identifier: GPL-3.0-or-later +# Destructive only inside an explicitly opted-in disposable test container. +set -eu +test "${EMBARASS_FIX_TEST:-}" = disposable-container +test -f /.dockerenv || test -f /run/.containerenv +test "$(id -u)" = 0 + +BIN=/fixtures/embarass +. /etc/os-release +openssl req -x509 -newkey rsa:2048 -nodes -days 1 \ + -subj /CN=emBarrass-Test-Enterprise-Root \ + -keyout /tmp/enterprise.key -out /tmp/enterprise.crt >/dev/null 2>&1 + +case "$ID" in + debian|ubuntu|alpine) + mkdir -p /usr/share/ca-certificates/embarass-test /usr/local/share/ca-certificates + cp /fixtures/aaa.pem /usr/share/ca-certificates/embarass-test/aaa.crt + cp /fixtures/emsign.pem /usr/share/ca-certificates/embarass-test/emsign.crt + cp /tmp/enterprise.crt /usr/local/share/ca-certificates/enterprise.crt + printf '# disposable test fixture\nembarass-test/aaa.crt\nembarass-test/emsign.crt\n' > /etc/ca-certificates.conf + /usr/sbin/update-ca-certificates --fresh >/tmp/seed.log 2>&1 + BUNDLE=/etc/ssl/certs/ca-certificates.crt + ;; + fedora|rhel) + # Isolate the seed from the current vendor's existing eMudhra distrust. + mv /usr/share/pki/ca-trust-source /tmp/original-vendor-ca-source + mkdir -p /usr/share/pki/ca-trust-source /etc/pki/ca-trust/source/anchors /etc/pki/ca-trust/source/blocklist + cp /fixtures/aaa.pem /etc/pki/ca-trust/source/anchors/aaa.pem + cp /fixtures/emsign.pem /etc/pki/ca-trust/source/anchors/emsign.pem + cp /tmp/enterprise.crt /etc/pki/ca-trust/source/anchors/enterprise.pem + /usr/bin/update-ca-trust extract >/tmp/seed.log 2>&1 + BUNDLE=/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem + ;; + *) echo "Unsupported smoke-test container: $ID"; exit 2 ;; +esac + +probe() { + want=$1 + for chain in emsign sectigo; do + set +e + "$BIN" --headless --chain "$chain" -- /usr/bin/curl -q --silent --output /dev/null \ + --max-time 5 https://example.com/ >/tmp/probe.log 2>&1 + actual=$? + set -e + # The generic wrapper cannot interpret arbitrary child exit codes. Newer + # curl can finish TLS then fail certificate verification without an alert. + if test "$want" = 0 && test "$actual" = 2 && + grep -q 'child_exit_code=60' /tmp/probe.log && + grep -q 'reason=no_tls_decision' /tmp/probe.log; then + actual=0 + fi + if test "$actual" != "$want"; then + cat /tmp/probe.log + echo "$ID $chain: expected exit $want, got $actual" + exit 1 + fi + done +} + +apply() { + set +e + "$BIN" fix --yes --headless >/tmp/fix.log 2>&1 + result=$? + set -e + # Root application intentionally leaves behavioral verification to the caller. + if test "$result" != 2 || ! grep -q 'REGENERATED' /tmp/fix.log; then + cat /tmp/fix.log + exit 1 + fi +} + +probe 1 +before=$(sha256sum "$BUNDLE") +"$BIN" fix --dry-run --headless >/tmp/preview.log 2>&1 +test "$before" = "$(sha256sum "$BUNDLE")" +apply +probe 0 +su -s /bin/sh nobody -c "$BIN fix --yes --headless" >/tmp/unprivileged-fix.log 2>&1 || { + cat /tmp/unprivileged-fix.log + exit 1 +} +grep -q 'BOTH FORGERIES REJECTED' /tmp/unprivileged-fix.log +openssl verify -CAfile "$BUNDLE" /tmp/enterprise.crt +"$BIN" fix --dry-run --headless >/tmp/noop.log 2>&1 +grep -q 'TARGET ROOTS ALREADY ABSENT' /tmp/noop.log +"$BIN" fix --undo --yes --headless >/tmp/undo.log 2>&1 +probe 1 + +if test "$ID" = fedora || test "$ID" = rhel; then + apply + cat /fixtures/aaa.pem /fixtures/emsign.pem > /etc/pki/ca-trust/source/blocklist/vendor-update.pem + /usr/bin/update-ca-trust extract + "$BIN" fix --undo --yes --headless >/tmp/undo-vendor.log 2>&1 + test -f /etc/pki/ca-trust/source/blocklist/vendor-update.pem + probe 0 +fi +echo "PASS $ID: preview, native repair, both trust paths, enterprise root, undo" diff --git a/pkg/runner/completion_test.go b/pkg/runner/completion_test.go new file mode 100644 index 0000000..acb4345 --- /dev/null +++ b/pkg/runner/completion_test.go @@ -0,0 +1,59 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package runner + +import ( + "context" + "testing" + "time" + + "github.com/boostsecurityio/emBarrass/pkg/intercept" + "github.com/stretchr/testify/require" +) + +func TestChildExitWaitsForTLSHandler(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + observations := make(chan intercept.Observation) + serverDone := make(chan error, 1) + // The child has exited, but the handler has not yet delivered its TLS alert. + // An unbuffered send makes receipt depend on the completion loop waiting. + go func() { + select { + case observations <- intercept.Observation{Kind: intercept.ObservationRejected, Host: "example.com"}: + serverDone <- nil + case <-ctx.Done(): + } + }() + result, err := finishRun(ctx, time.Now(), observationState{connected: true}, nil, observations, serverDone, nil) + require.NoError(t, err) + require.Equal(t, OutcomeRejected, result.Outcome) + require.Equal(t, ReasonForgedTLSRejected, result.Reason) +} + +func TestChildExitDrainsCompletedHandler(t *testing.T) { + t.Parallel() + observations := make(chan intercept.Observation, 1) + observations <- intercept.Observation{Kind: intercept.ObservationAccepted, Host: "example.com"} + serverDone := make(chan error, 1) + serverDone <- nil + result, err := finishRun(context.Background(), time.Now(), observationState{}, nil, observations, serverDone, nil) + require.NoError(t, err) + require.Equal(t, OutcomeVulnerable, result.Outcome) +} + +func TestChildExitStillHonorsTimeoutAndCancellation(t *testing.T) { + t.Parallel() + timeout := make(chan time.Time, 1) + timeout <- time.Now() + result, err := finishRun(context.Background(), time.Now(), observationState{}, nil, nil, nil, timeout) + require.NoError(t, err) + require.Equal(t, OutcomeInconclusive, result.Outcome) + require.Equal(t, ReasonTimeout, result.Reason) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err = finishRun(ctx, time.Now(), observationState{}, nil, nil, nil, nil) + require.ErrorIs(t, err, context.Canceled) +} diff --git a/pkg/runner/runner.go b/pkg/runner/runner.go index dce9e38..a13215f 100644 --- a/pkg/runner/runner.go +++ b/pkg/runner/runner.go @@ -203,11 +203,13 @@ func Run(ctx context.Context, options Options) (Result, error) { return vulnerableResult(startedAt, state, childErr), nil } case childErr := <-processDone: - state = drainObservations(ctx, state, server.Observations()) - if state.accepted { - return vulnerableResult(startedAt, state, childErr), nil + // Stop accepting connections, then let existing handlers record the + // child's final TLS alert. Canceling their context here would create + // artificial handshake failures; a nonblocking drain races the alert. + if err := server.Close(); err != nil { + return Result{}, fmt.Errorf("close interceptor after child exit: %w", err) } - return completedResult(startedAt, state, childErr), nil + return finishRun(ctx, startedAt, state, childErr, server.Observations(), serverErrors, timeout) case serverErr := <-serverErrors: if serverErr == nil { serverErrors = nil @@ -244,6 +246,38 @@ func Run(ctx context.Context, options Options) (Result, error) { } } +func finishRun(ctx context.Context, startedAt time.Time, state observationState, childErr error, + observations <-chan intercept.Observation, serverErrors <-chan error, timeout <-chan time.Time, +) (Result, error) { + for { + select { + case observation := <-observations: + state = applyObservation(ctx, state, observation) + if state.accepted { + return vulnerableResult(startedAt, state, childErr), nil + } + case err := <-serverErrors: + if err != nil { + return Result{}, fmt.Errorf("finish local interceptor: %w", err) + } + state = drainObservations(ctx, state, observations) + if state.accepted { + return vulnerableResult(startedAt, state, childErr), nil + } + return completedResult(startedAt, state, childErr), nil + case <-timeout: + state = drainObservations(ctx, state, observations) + if state.accepted { + return vulnerableResult(startedAt, state, childErr), nil + } + return Result{Outcome: OutcomeInconclusive, Reason: ReasonTimeout, Host: state.host, + ChildExitCode: exitCode(childErr), Duration: time.Since(startedAt)}, nil + case <-ctx.Done(): + return Result{}, fmt.Errorf("finish wrapped command: %w", context.Cause(ctx)) + } + } +} + func proxyListenHost(target ProxyTarget) (string, error) { switch target { case ProxyTargetHost: From 0b7b5f8db85be8f73b16439a1c39679edb6c4d6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Proulx?= <76956526+fproulx-boostsecurity@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:09:01 -0400 Subject: [PATCH 2/3] test: make repair fixtures independent of checkout line endings --- pkg/repair/bundle_test.go | 82 +++++++++++++++++++++++++-------------- 1 file changed, 52 insertions(+), 30 deletions(-) diff --git a/pkg/repair/bundle_test.go b/pkg/repair/bundle_test.go index f620355..cfb4c7c 100644 --- a/pkg/repair/bundle_test.go +++ b/pkg/repair/bundle_test.go @@ -4,6 +4,7 @@ package repair import ( + "bytes" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" @@ -34,7 +35,9 @@ func affectedRoot(t *testing.T, name string) []byte { t.Helper() data, err := os.ReadFile("testdata/" + name + ".pem") require.NoError(t, err) - return data + // Tests choose their input line endings explicitly, independently of Git's + // checkout conversion (notably core.autocrlf on Windows). + return bytes.ReplaceAll(data, []byte("\r\n"), []byte("\n")) } func fixtureBundle(t *testing.T) []byte { @@ -47,24 +50,37 @@ func fixtureBundle(t *testing.T) []byte { func TestInspectRemovesExactCertificatesPreservingOtherBytes(t *testing.T) { t.Parallel() - trusted := ordinaryRoot(t, "Enterprise test root") - before := "### metadata\r\n" - between := "\r\n# not a trust anchor\n" - after := "\n# end of bundle\n" - data := append([]byte(before), trusted...) - data = append(data, []byte(between)...) - data = append(data, affectedRoot(t, "aaa")...) - data = append(data, affectedRoot(t, "emsign")...) - data = append(data, []byte(after)...) - plan, err := inspect(data) - require.NoError(t, err) - require.Len(t, plan.Removed, 2) - require.Equal(t, 3, plan.Certificates) - require.Equal(t, before+string(trusted)+between+"\n\n"+after, string(plan.replacement)) - again, err := inspect(plan.replacement) - require.NoError(t, err) - require.Empty(t, again.Removed) - require.Equal(t, again.original, again.replacement) + for _, test := range []struct { + name, trustedEOL, aaaEOL, emsignEOL string + }{ + {"LF", "\n", "\n", "\n"}, + {"CRLF", "\r\n", "\r\n", "\r\n"}, + {"mixed", "\r\n", "\n", "\r\n"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + trusted := bytes.ReplaceAll(ordinaryRoot(t, "Enterprise test root"), []byte("\n"), []byte(test.trustedEOL)) + aaa := bytes.ReplaceAll(affectedRoot(t, "aaa"), []byte("\n"), []byte(test.aaaEOL)) + emsign := bytes.ReplaceAll(affectedRoot(t, "emsign"), []byte("\n"), []byte(test.emsignEOL)) + before := "### metadata\r\n" + between := "\r\n# not a trust anchor\n" + after := "\n# end of bundle\n" + data := append([]byte(before), trusted...) + data = append(data, []byte(between)...) + data = append(data, aaa...) + data = append(data, emsign...) + data = append(data, []byte(after)...) + plan, err := inspect(data) + require.NoError(t, err) + require.Len(t, plan.Removed, 2) + require.Equal(t, 3, plan.Certificates) + require.Equal(t, before+string(trusted)+between+test.aaaEOL+test.emsignEOL+after, string(plan.replacement)) + again, err := inspect(plan.replacement) + require.NoError(t, err) + require.Empty(t, again.Removed) + require.Equal(t, again.original, again.replacement) + }) + } } func TestInspectRejectsMalformedAndAmbiguousBundles(t *testing.T) { @@ -94,15 +110,21 @@ func TestInspectRemovesDuplicateAffectedCertificates(t *testing.T) { func TestLegacyNegativeSerialRootIsPreservedExactly(t *testing.T) { t.Parallel() - legacy := affectedRoot(t, "legacy-negative-serial") - data := append(append([]byte{}, legacy...), affectedRoot(t, "aaa")...) - plan, err := inspect(data) - require.NoError(t, err) - require.Len(t, plan.Removed, 1) - require.Equal(t, string(legacy)+"\n", string(plan.replacement)) - block, _ := pem.Decode(legacy) - before := append([]byte{}, block.Bytes...) - _, err = parseBundleCertificate(block.Bytes) - require.NoError(t, err) - require.Equal(t, before, block.Bytes, "compatibility validation must never mutate input DER") + for name, eol := range map[string]string{"LF": "\n", "CRLF": "\r\n"} { + t.Run(name, func(t *testing.T) { + t.Parallel() + legacy := bytes.ReplaceAll(affectedRoot(t, "legacy-negative-serial"), []byte("\n"), []byte(eol)) + aaa := bytes.ReplaceAll(affectedRoot(t, "aaa"), []byte("\n"), []byte(eol)) + data := append(append([]byte{}, legacy...), aaa...) + plan, err := inspect(data) + require.NoError(t, err) + require.Len(t, plan.Removed, 1) + require.Equal(t, string(legacy)+eol, string(plan.replacement)) + block, _ := pem.Decode(legacy) + before := append([]byte{}, block.Bytes...) + _, err = parseBundleCertificate(block.Bytes) + require.NoError(t, err) + require.Equal(t, before, block.Bytes, "compatibility validation must never mutate input DER") + }) + } } From e973b390ea75a60a229014046021fa2a02fb6a0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Proulx?= <76956526+fproulx-boostsecurity@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:22:06 -0400 Subject: [PATCH 3/3] feat: explain per-tool trust and remediation in batch results --- README.md | 26 ++++ cmd/embarass/batch.go | 22 +++- cmd/embarass/batch_remediation.go | 173 +++++++++++++++++++++++++ cmd/embarass/batch_remediation_test.go | 119 +++++++++++++++++ cmd/embarass/batch_terminal.go | 57 +++++--- cmd/embarass/root.go | 1 + 6 files changed, 381 insertions(+), 17 deletions(-) create mode 100644 cmd/embarass/batch_remediation.go create mode 100644 cmd/embarass/batch_remediation_test.go diff --git a/README.md b/README.md index 3833300..87997b0 100644 --- a/README.md +++ b/README.md @@ -345,6 +345,32 @@ probe rejected the forged chain. Tools absent from `PATH` do not affect the exit code. Canceling before the first probe also exits `0`; canceling a partial sweep exits `2` unless a vulnerability was already confirmed. +### Understanding partial exposure + +Interactive batches with exposed tools stay open at the result screen. Press +**d** for per-tool explanations, **left/right** to switch exposed tools, and +**up/down** or **Page Up/Page Down** to scroll. **d** or **Escape** returns to the +summary; **q** or **Enter** exits with the recorded verdict. Opening details does +not run commands, change trust, or turn the result into a cancellation. + +Use `embarass batch --details` to open explanations immediately, or +`embarass batch --yes --headless --details` to include them in plain logs. + +Different results can reflect different trust sources: + +| Path | What to do | +|---|---| +| System/OpenSSL CA bundles | Vendor CA updates or `fix` may help clients such as curl, git, gem, and cargo when their build uses the selected store. Overrides and other builds may differ. | +| Bundled roots, runtimes, or trust-library dependencies | Update the tool with its original installer. For Homebrew installations, examples include `brew update` followed by `brew upgrade awscli`, `python`, `node`, or `uv`; use the actual installed formula/cask name, including versioned names. An improved result after upgrading does not prove the roots were bundled. | +| gcloud's SDK trust | Update the SDK or explicitly select a verified patched CA file. On macOS, after confirming the system bundle is repaired, `export CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE=/etc/ssl/cert.pem` applies to that shell and its children. Include required enterprise CAs. Batch isolates saved gcloud configuration but inherits this environment variable. | +| .NET native trust on macOS | PEM repair does not modify Keychain trust. Update macOS and .NET and retest; remaining exposure needs separate native-trust remediation. Sharing trust anchors with Safari does not guarantee the same validation policy. | +| Container trust | Update and rebuild the actual workload image. Host repair cannot fix the intentionally historical `docker/git` fixture. | + +The details identify **likely trust paths**, not detected CA configuration or +package-manager ownership. Acceptance is observed; its exact cause needs +tool-specific investigation. Sources: [gcloud custom CA configuration](https://docs.cloud.google.com/sdk/docs/proxy-settings), +[.NET Apple chain validation](https://github.com/dotnet/runtime/blob/v10.0.0/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Apple.cs). + ### Git HTTPS transport pinning Git can use `url.*.insteadOf` configuration to silently rewrite an explicit HTTPS remote to SSH. That would bypass a TLS test and previously produced an inconclusive result. For wrapped Git commands, emBarrass now transparently makes an implicit HTTPS port explicit (`:443`) and adds an exact, invocation-local identity rule. This keeps the command on HTTPS without disabling or replacing any Git CA, verification, proxy, credential, or other configuration. Explicit SSH URLs remain unchanged. diff --git a/cmd/embarass/batch.go b/cmd/embarass/batch.go index 16e7af5..2b27467 100644 --- a/cmd/embarass/batch.go +++ b/cmd/embarass/batch.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "runtime" "strings" "time" @@ -30,10 +31,15 @@ commands, ask for confirmation, and run the probes sequentially. Each probe uses a public endpoint. The intercepted request is never forwarded upstream, child output is discarded, and cache writes use an automatically deleted temporary workspace. The docker/git probe may pull and retain one -immutable, digest-pinned image.`, +immutable, digest-pinned image. + +Exposed interactive results stay open: press d for per-tool trust and repair +details, then q to exit. Use --details to open them immediately or include them +in headless output. Explanations do not change configuration or run repairs.`, Example: fmt.Sprintf(` %[1]s batch %[1]s batch --chain emsign %[1]s batch --yes --headless + %[1]s batch --yes --headless --details # Completely or partially embarrassed? Preview, repair, and recheck %[1]s fix --dry-run @@ -45,6 +51,7 @@ immutable, digest-pinned image.`, }, } command.Flags().BoolVarP(&app.batchYes, "yes", "y", false, "run the displayed probes without prompting") + command.Flags().BoolVar(&app.batchDetails, "details", false, "explain exposed tools' trust sources, repair coverage, and remediation") command.Flags().DurationVar(&app.timeout, "timeout", defaultTimeout, "maximum runtime per tool and trust path; 0 disables the deadline") command.Flags().StringVar(&app.chain, "chain", chainAll, chainFlagUsage) registerChainCompletion(command) @@ -115,6 +122,8 @@ func (app *application) runBatchTerminal( app.batchYes, ) model.invocation = app.displayedInvocation() + model.reviewResults = true + model.detailsExpanded = app.batchDetails program := tea.NewProgram( model, tea.WithInput(cmd.InOrStdin()), @@ -156,6 +165,13 @@ func (app *application) runBatchHeadless( result, reportedChains, err := runChains(ctx, app.run, batchRunnerOptions(plan, probe, app.timeout), chains, nil) summary.record(result, err) logBatchResult(log, probe.Name, result, reportedChains, err) + if app.batchDetails && err == nil && result.Outcome == runner.OutcomeVulnerable { + guidance := remediationFor(probe, runtime.GOOS, app.displayedInvocation()) + log.Warn().Str("tool", probe.Name).Str("trust_path", guidance.cause). + Str("fix_coverage", guidance.coverage).Str("remediation", guidance.remediation). + Strs("commands", guidance.commands).Str("details", guidance.details). + Msg("REMEDIATION: acceptance confirmed; trust source is guidance, not detected configuration") + } } log.Info(). Int("embarrassed", summary.vulnerable). @@ -166,6 +182,10 @@ func (app *application) runBatchHeadless( Msg("BATCH COMPLETE") if summary.vulnerable > 0 { app.logRepairCallToAction(log) + if !app.batchDetails { + log.Info().Str("command", app.displayedInvocation()+" batch --yes --headless --details"). + Msg("Rerun with per-tool root-cause and remediation guidance") + } } return summary } diff --git a/cmd/embarass/batch_remediation.go b/cmd/embarass/batch_remediation.go new file mode 100644 index 0000000..ebb21a4 --- /dev/null +++ b/cmd/embarass/batch_remediation.go @@ -0,0 +1,173 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "fmt" + "strings" + + "github.com/boostsecurityio/emBarrass/pkg/batchtest" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// Guidance describes known trust mechanisms, not a claim that batch inspected +// a client's CA configuration or detected its installation/package manager. +type remediation struct { + cause, coverage, remediation, details string + commands []string +} + +func remediationFor(probe batchtest.Probe, platform, invocation string) remediation { + invocation = displayedInvocation(invocation) + r := remediation{ + cause: "Trust depends on this tool's build, runtime, and CA configuration. Batch confirms acceptance but does not identify the exact CA source.", + coverage: "fix repairs a supported system CA store. It does not update installed applications or their private trust stores.", + remediation: "Update this tool through the installer or package manager you used, then rerun batch. If still exposed, check its CA overrides and runtime trust settings.", + details: "A package update can refresh bundled roots, a runtime, or a trust-library dependency. A better result after upgrading does not by itself prove which changed. TRUST HELD only covers the paths tested in that run.", + commands: []string{invocation + " batch"}, + } + if probe.Containerized { + r.cause = "This process uses trust inside its container. The docker/git probe deliberately uses a historical, digest-pinned vulnerable image." + r.coverage = "Host repair and host package upgrades do not repair this container image." + r.remediation = "For your workloads, update CA packages in the image, rebuild, and redeploy. Test the replacement image's actual client." + r.details = "The built-in historical fixture can remain EMBARRASSED after a successful host repair. Its result is not evidence that the host repair failed." + r.commands = nil + return r + } + switch probe.Name { + case "gcloud": + r.cause = "The Google Cloud SDK normally supplies its own CA bundle; changing /etc/ssl/cert.pem alone need not affect it." + r.coverage = "fix does not edit the SDK bundle. gcloud can be configured to use a repaired CA file." + r.remediation = "Update the SDK through its original installer. Alternatively, point CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE at a verified, patched bundle that includes any required enterprise CAs." + r.details = "Batch uses a temporary gcloud configuration to isolate credentials, so saved gcloud config properties are not loaded. It inherits the CA environment variable. An export affects this shell and its child processes; repeat the setting where you actually run gcloud." + if platform == "darwin" { + r.commands = []string{invocation + " fix --dry-run", "export CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE=/etc/ssl/cert.pem", invocation + " batch"} + r.remediation += " For the commands below, first confirm fix --dry-run says TARGET ROOTS ALREADY ABSENT; otherwise apply fix and verify it before setting the override." + } + case "dotnet": + switch platform { + case "darwin": + r.cause = ".NET on macOS uses Apple's native trust APIs and Keychain trust. Sharing trust anchors with Safari does not guarantee the same certificate-validation policy." + r.coverage = "The macOS PEM repair does not change Keychain trust. SSL_CERT_FILE is not a remedy for this native trust path." + r.remediation = "Update macOS and the .NET SDK/runtime, then recheck. If exposure remains, explicit native distrust needs a separate, reviewed Keychain change; this is not implemented by fix." + r.details = "Acceptance here does not identify which revocation or policy check was missing. Do not assume Safari's protection covers this client, and do not disable TLS verification as a workaround." + case "linux": + r.cause = ".NET on Linux generally uses OpenSSL and system trust. Its configuration and container boundary still matter." + r.coverage = "Native Linux CA-package updates or fix on a supported distribution may help this trust path. Recheck the actual client." + default: + r.cause = ".NET uses platform-native trust; the macOS PEM repair does not apply to Windows." + } + case "curl", "git", "gem", "cargo", "wget", "composer": + if platform == "darwin" || platform == "linux" { + r.cause = "These clients can use system/OpenSSL CA bundles. Their build and CA overrides determine whether they consult the store repaired by fix." + r.coverage = "System-store repair may help. curl, git, gem, and cargo improved in our macOS testing; this is not a guarantee for every installation." + r.remediation = "Prefer vendor CA-package and tool updates. For emergency mitigation, preview and apply fix on a supported system, then rerun batch. If still exposed, inspect this tool's CA configuration." + r.commands = []string{invocation + " fix --dry-run", invocation + " fix", invocation + " batch"} + } + case "aws", "python", "pip", "node", "npm", "pnpm", "uv", "httpie": + r.cause = "This tool may use bundled roots, a Python/Node runtime trust set, system trust, or an override. The choice varies by version and distribution." + r.coverage = "A package/runtime update may be needed even after system repair. fix does not rewrite private CA bundles." + if platform == "darwin" { + r.remediation = "If installed with Homebrew, update Homebrew's package metadata and upgrade the installed formula/cask, then rerun batch. Otherwise use the original installer." + formula := map[string]string{"aws": "awscli", "python": "python", "node": "node", "uv": "uv"}[probe.Name] + if formula != "" { + r.commands = []string{"brew update", "brew upgrade " + formula, invocation + " batch"} + r.details += " The Homebrew commands are examples, not detected installation advice. Use your installed formula name, such as python@X.Y or node@X, when version-pinned." + } + } + } + if platform != "darwin" && platform != "linux" { + r.coverage = "fix does not support this platform. Use OS and application trust updates, then recheck." + } + return r +} + +func (model batchModel) exposedItems() []batchItem { + var items []batchItem + for _, item := range model.items { + if item.state == batchVulnerable { + items = append(items, item) + } + } + return items +} + +func (model batchModel) reviewKey(key string) (tea.Model, tea.Cmd) { + if key == "q" || key == "enter" || key == "ctrl+c" || (key == "esc" && !model.detailsExpanded) { + return model, tea.Quit // Reviewing a completed result is not cancellation. + } + if len(model.exposedItems()) == 0 { + return model, nil + } + if key == "d" || key == "esc" { + model.detailsExpanded = !model.detailsExpanded + model.detailScroll = 0 + return model, nil + } + if !model.detailsExpanded { + return model, nil + } + switch key { + case "right", "tab", "n": + model.detailIndex = (model.detailIndex + 1) % len(model.exposedItems()) + model.detailScroll = 0 + case "left", "shift+tab", "p": + model.detailIndex = (model.detailIndex + len(model.exposedItems()) - 1) % len(model.exposedItems()) + model.detailScroll = 0 + case "down", "j": + model.detailScroll++ + case "up", "k": + model.detailScroll-- + case "pgdown", " ": + model.detailScroll += model.detailPageSize() + case "pgup": + model.detailScroll -= model.detailPageSize() + case "home": + model.detailScroll = 0 + case "end": + model.detailScroll = len(model.remediationLines()) + } + model.detailScroll = max(0, min(model.detailScroll, len(model.remediationLines())-model.detailPageSize())) + return model, nil +} + +func (model batchModel) detailPageSize() int { return max(3, model.height-9) } + +func (model batchModel) remediationLines() []string { + items := model.exposedItems() + item := items[model.detailIndex%len(items)] + r := remediationFor(item.probe, model.platform, model.invocation) + width := max(20, min(model.width-4, 90)) + wrap := lipgloss.NewStyle().Width(width).Render + sections := []string{ + model.styles.redBold.Render("OBSERVED") + " Forged TLS accepted; application data seen.", + model.styles.muted.Render("Mixed results can reflect different stores. The trust path below is guidance, not a configuration audit."), "", + model.styles.cyanBold.Render("LIKELY TRUST PATH"), r.cause, "", + model.styles.yellowBold.Render("WHAT FIX COVERS"), r.coverage, "", + model.styles.greenBold.Render("REMEDIATION"), r.remediation, + } + if len(r.commands) > 0 { + sections = append(sections, "", model.styles.cyanBold.Render("COMMANDS TO RUN YOURSELF")) + for _, command := range r.commands { + sections = append(sections, model.styles.cyan.Render(command)) + } + } + sections = append(sections, "", model.styles.cyanBold.Render("DETAILS"), r.details) + return strings.Split(wrap(strings.Join(sections, "\n")), "\n") +} + +func (model batchModel) remediationView() string { + items := model.exposedItems() + item := items[model.detailIndex%len(items)] + lines := model.remediationLines() + start := max(0, min(model.detailScroll, len(lines)-model.detailPageSize())) + end := min(len(lines), start+model.detailPageSize()) + heading := model.styles.cyanBold.Render("WHY STILL EXPOSED?") + "\n" + + model.styles.redBold.Render(fmt.Sprintf("%s · %d/%d exposed tools", item.probe.Name, model.detailIndex+1, len(items))) + body := strings.Join(lines[start:end], "\n") + footer := model.styles.muted.Render(fmt.Sprintf("Lines %d–%d/%d · guidance only; no changes made", start+1, end, len(lines))) + "\n" + + model.styles.cyanBold.Render("←/→ tool · ↑/↓ scroll · d/esc back · q exit") + return lipgloss.NewStyle().Width(max(20, model.width-4)).MarginLeft(2).Render(heading + "\n\n" + body + "\n\n" + footer) +} diff --git a/cmd/embarass/batch_remediation_test.go b/cmd/embarass/batch_remediation_test.go new file mode 100644 index 0000000..7062fb8 --- /dev/null +++ b/cmd/embarass/batch_remediation_test.go @@ -0,0 +1,119 @@ +// Copyright (C) 2026 boostsecurity.io +// SPDX-License-Identifier: GPL-3.0-or-later + +package main + +import ( + "bytes" + "context" + "strings" + "testing" + "time" + + "github.com/boostsecurityio/emBarrass/pkg/batchtest" + "github.com/boostsecurityio/emBarrass/pkg/runner" + tea "github.com/charmbracelet/bubbletea" + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" +) + +func TestBatchReviewDoesNotRunCommandsOrChangeVerdict(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + model := newBatchModel(ctx, cancel, newTerminalUI(testWriter{t}).styles, + batchtest.Plan{Probes: []batchtest.Probe{{Name: "curl"}, {Name: "gcloud"}, {Name: "dotnet"}}}, + func(context.Context, runner.Options) (runner.Result, error) { + t.Fatal("review must not execute probes or repairs") + return runner.Result{}, nil + }, time.Second, false) + model.reviewResults, model.confirmed = true, true + model.platform, model.invocation = "darwin", "./embarass" + model.items[0].state, model.items[0].result.Outcome = batchRejected, runner.OutcomeRejected + model.items[1].state, model.items[1].result.Outcome = batchVulnerable, runner.OutcomeVulnerable + updated, cmd := model.Update(batchResultMsg{index: 2, result: runner.Result{Outcome: runner.OutcomeVulnerable}}) + model = updated.(batchModel) + require.Nil(t, cmd, "exposed interactive results stay open for review") + require.True(t, model.done) + require.Contains(t, model.View(), "PARTIALLY EMBARRASSED") + require.Contains(t, model.View(), "[d] WHY STILL EXPOSED?") + updated, cmd = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'d'}}) + model = updated.(batchModel) + require.Nil(t, cmd) + require.Contains(t, model.View(), "gcloud · 1/2") + require.NotContains(t, model.View(), "curl ·") + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyRight}) + model = updated.(batchModel) + require.Contains(t, model.View(), "dotnet · 2/2") + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyEnd}) + model = updated.(batchModel) + require.Positive(t, model.detailScroll) + require.Contains(t, model.View(), "DETAILS") + updated, _ = model.Update(tea.WindowSizeMsg{Width: 50, Height: 20}) + model = updated.(batchModel) + require.Zero(t, model.detailScroll) + updated, _ = model.Update(tea.KeyMsg{Type: tea.KeyEsc}) + model = updated.(batchModel) + require.False(t, model.detailsExpanded) + updated, cmd = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'q'}}) + model = updated.(batchModel) + require.NotNil(t, cmd) + require.False(t, model.canceled) + require.NoError(t, ctx.Err()) + require.Equal(t, exitVulnerable, model.summary().exitCode()) +} + +func TestRemediationCoverageDependsOnPlatformAndContainer(t *testing.T) { + t.Parallel() + mac := remediationFor(batchtest.Probe{Name: "dotnet"}, "darwin", "./embarass") + require.Contains(t, mac.coverage, "does not change Keychain") + require.NotContains(t, strings.Join(mac.commands, "\n"), " fix") + linux := remediationFor(batchtest.Probe{Name: "dotnet"}, "linux", "./embarass") + require.Contains(t, linux.coverage, "supported distribution") + windows := remediationFor(batchtest.Probe{Name: "curl"}, "windows", "embarass.exe") + require.Contains(t, windows.coverage, "does not support") + require.NotContains(t, strings.Join(windows.commands, "\n"), " fix") + container := remediationFor(batchtest.Probe{Name: "docker/git", Containerized: true}, "darwin", "./embarass") + require.Contains(t, container.details, "not evidence that the host repair failed") + require.Empty(t, container.commands) + gcloud := remediationFor(batchtest.Probe{Name: "gcloud"}, "darwin", "./embarass") + require.Contains(t, gcloud.details, "saved gcloud config properties are not loaded") + require.Contains(t, gcloud.commands, "export CLOUDSDK_CORE_CUSTOM_CA_CERTS_FILE=/etc/ssl/cert.pem") + for tool, formula := range map[string]string{"aws": "awscli", "python": "python", "node": "node", "uv": "uv"} { + guide := remediationFor(batchtest.Probe{Name: tool}, "darwin", "./embarass") + require.Contains(t, guide.commands, "brew upgrade "+formula) + require.Contains(t, guide.remediation, "If installed with Homebrew") + } +} + +func TestHeldBatchStillExitsWithoutReview(t *testing.T) { + t.Parallel() + model := batchModel{reviewResults: true, confirmed: true, items: []batchItem{{probe: batchtest.Probe{Name: "curl"}}}} + updated, cmd := model.Update(batchResultMsg{index: 0, result: runner.Result{Outcome: runner.OutcomeRejected}}) + require.NotNil(t, cmd) + require.True(t, updated.(batchModel).done) +} + +func TestHeadlessDetailsDescribeExposureWithoutExtraProbes(t *testing.T) { + t.Parallel() + for _, details := range []bool{false, true} { + var output bytes.Buffer + log := zerolog.New(&output) + calls := 0 + app := application{batchDetails: details, invocation: "./embarass", run: func(context.Context, runner.Options) (runner.Result, error) { + calls++ + return runner.Result{Outcome: runner.OutcomeVulnerable}, nil + }} + plan := batchtest.Plan{Probes: []batchtest.Probe{{Name: "gcloud", Executable: "gcloud"}}} + summary := app.runBatchHeadless(log.WithContext(context.Background()), plan, allChains) + require.Equal(t, 1, calls) + require.Equal(t, exitVulnerable, summary.exitCode()) + if details { + require.Contains(t, output.String(), "SDK normally supplies its own CA bundle") + require.Contains(t, output.String(), "saved gcloud config properties are not loaded") + } else { + require.NotContains(t, output.String(), "SDK normally supplies its own CA bundle") + require.Contains(t, output.String(), "batch --yes --headless --details") + } + } +} diff --git a/cmd/embarass/batch_terminal.go b/cmd/embarass/batch_terminal.go index 49d691f..8a53fb2 100644 --- a/cmd/embarass/batch_terminal.go +++ b/cmd/embarass/batch_terminal.go @@ -6,6 +6,7 @@ package main import ( "context" "fmt" + "runtime" "strings" "time" @@ -40,21 +41,27 @@ type batchItem struct { } type batchModel struct { - ctx context.Context - cancel context.CancelFunc - styles terminalStyles - plan batchtest.Plan - run runFunc - timeout time.Duration - invocation string - items []batchItem - current int - spinner int - width int - autoStart bool - confirmed bool - done bool - canceled bool + ctx context.Context + cancel context.CancelFunc + styles terminalStyles + plan batchtest.Plan + run runFunc + timeout time.Duration + invocation string + items []batchItem + current int + spinner int + width int + autoStart bool + confirmed bool + done bool + canceled bool + reviewResults bool + detailsExpanded bool + detailIndex int + detailScroll int + height int + platform string } type batchStartMsg struct{} @@ -87,6 +94,8 @@ func newBatchModel( timeout: timeout, items: items, width: 80, + height: 30, + platform: runtime.GOOS, autoStart: autoStart, } } @@ -102,9 +111,14 @@ func (model batchModel) Update(message tea.Msg) (tea.Model, tea.Cmd) { switch message := message.(type) { case tea.WindowSizeMsg: model.width = message.Width + model.height = message.Height + model.detailScroll = 0 return model, nil case tea.KeyMsg: key := strings.ToLower(message.String()) + if model.done { + return model.reviewKey(key) + } if !model.confirmed { if key == "y" { return model.begin() @@ -132,7 +146,7 @@ func (model batchModel) Update(message tea.Msg) (tea.Model, tea.Cmd) { model.spinner = (model.spinner + 1) % len(batchSpinnerFrames) return model, batchSpinnerTick() case batchResultMsg: - if message.index < 0 || message.index >= len(model.items) { + if model.done || message.index < 0 || message.index >= len(model.items) { return model, nil } item := &model.items[message.index] @@ -143,6 +157,9 @@ func (model batchModel) Update(message tea.Msg) (tea.Model, tea.Cmd) { model.current = message.index + 1 if model.current >= len(model.items) { model.done = true + if model.reviewResults && model.summary().vulnerable > 0 { + return model, nil + } return model, tea.Quit } model.items[model.current].state = batchRunning @@ -197,6 +214,9 @@ func batchState(result runner.Result, err error) batchItemState { } func (model batchModel) View() string { + if model.done && !model.canceled && model.detailsExpanded && model.summary().vulnerable > 0 { + return model.remediationView() + } logoText := terminalLogo if model.width > 0 && model.width < 70 { logoText = "emBarrass // BATCH TLS TRUST SWEEP" @@ -272,6 +292,11 @@ func (model batchModel) View() string { } if (model.done || model.canceled) && model.summary().vulnerable > 0 { lines = append(lines, "", repairCallToAction(model.styles, model.invocation, model.width-4)) + if model.reviewResults && !model.canceled { + lines = append(lines, "", " "+model.styles.yellowBold.Render("[d] WHY STILL EXPOSED?"), + " "+model.styles.muted.Render("Root cause · update vs system repair · per-tool next steps"), + " "+model.styles.muted.Render("Enter or q exits with the recorded result.")) + } } return strings.Join(lines, "\n") } diff --git a/cmd/embarass/root.go b/cmd/embarass/root.go index e904a5d..ada35db 100644 --- a/cmd/embarass/root.go +++ b/cmd/embarass/root.go @@ -37,6 +37,7 @@ type application struct { verbose bool headless bool batchYes bool + batchDetails bool terminalStarted bool timeout time.Duration chain string