diff --git a/.gitattributes b/.gitattributes index 99799b2..9c6e8e9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,6 @@ # Prevents gofmt/gofumpt/goimports CRLF false positives on Windows CI. # See: golangci/golangci-lint#580, golang/go#16355 * text=auto eol=lf + +# Goldens are compared byte for byte, so git must never rewrite their line endings. +*.golden -text diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 273e491..cfbb505 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,7 +22,7 @@ jobs: - uses: actions/setup-go@v7 with: - go-version-file: go.mod + go-version: '1.20.x' - name: Build run: go build -v ./... diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 2a3965f..54298be 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/setup-go@v7 with: - go-version-file: go.mod + go-version: '1.20.x' - name: Check Go version constraint if: matrix.os == 'ubuntu-latest' @@ -32,12 +32,10 @@ jobs: echo "::error::Current value: go $GO_VERSION" exit 1 fi - - - name: Check spelling - if: matrix.os == 'ubuntu-latest' - uses: crate-ci/typos@master - with: - config: ./.typos.toml + if grep -q '^toolchain' go.mod; then + echo "::error::go.mod must not carry a toolchain line (keeps the module on Go 1.20)" + exit 1 + fi - name: golangci-lint uses: golangci/golangci-lint-action@v8 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d9a4e14..d16926c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -41,7 +41,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v7 with: - go-version-file: go.mod + go-version: '1.20.x' - name: Set up Zig uses: mlugg/setup-zig@v2 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8506127..ae7d0b1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-go@v7 with: - go-version-file: go.mod + go-version: '1.20.x' - name: Run tests if: matrix.os == 'windows-latest' diff --git a/.gitignore b/.gitignore index 8c3e789..b42336a 100644 --- a/.gitignore +++ b/.gitignore @@ -24,7 +24,6 @@ !.gitignore !.golangci.yml !.goreleaser.yml -!.typos.toml !CLAUDE.md !LICENSE @@ -45,6 +44,9 @@ # === RFCs === !rfcs/*.md +# === Test goldens === +!**/testdata/*.golden + # === Always ignore (override !*/) === .git/ .idea/ diff --git a/.golangci.yml b/.golangci.yml index f68df0c..43e7692 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -47,6 +47,7 @@ linters: - nakedret - predeclared - revive + - tagliatelle - testifylint - unconvert - unparam @@ -151,6 +152,12 @@ linters: - name: unexported-return - name: unused-parameter disabled: true + tagliatelle: + case: + use-field-name: true + rules: + json: snake + csv: snake staticcheck: checks: - "all" @@ -184,6 +191,9 @@ linters: - path: "masterkey/gcoredump_darwin.go" linters: - gocognit + - path-except: "^internal/(record|masterkey|snapshot)/" + linters: + - tagliatelle formatters: enable: diff --git a/.typos.toml b/.typos.toml deleted file mode 100644 index 4d7a695..0000000 --- a/.typos.toml +++ /dev/null @@ -1,10 +0,0 @@ -# See https://github.com/crate-ci/typos/blob/master/docs/reference.md to configure typos -[default.extend-words] -Readed = "Readed" -Sie = "Sie" -OT = "OT" -Encrypter = "Encrypter" -Decrypter = "Decrypter" -PASSWOR = "PASSWOR" -[files] -extend-exclude = ["go.mod", "go.sum"] \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md index 21c9ee4..b720a55 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ This project is for security research and defensive purposes only. Do not genera ## Project Overview -HackBrowserData is a CLI security research tool for extracting and decrypting browser data across Windows, macOS, and Linux. It supports Chromium-based browsers and Firefox. +HackBrowserData is a CLI security research tool for extracting and decrypting browser data across Windows, macOS, and Linux. It supports Chromium-based browsers, Firefox, and Safari. **Constraint**: Must build with Go 1.20 (Windows 7 support). Do not use features from Go 1.21+ (e.g., `log/slog`, `slices`, `maps`, `cmp` packages). @@ -33,9 +33,6 @@ golangci-lint run gofumpt -l -w . goimports -w -local github.com/moond4rk/hackbrowserdata . -# Spelling -typos - # Dependencies (MUST use go@1.20 to avoid bumping go directive) # export GOROOT=$(brew --prefix go@1.20)/libexec && export PATH=$GOROOT/bin:$PATH go mod tidy @@ -62,14 +59,14 @@ make payload-clean # rm crypto/*.bin - **C payload**: all sources in `crypto/windows/abe_native/` are first-party (no vendored C). See RFC-010 §9.2 for why Stephen Fewer's reflective loader was rejected. - **Error handling**: `fmt.Errorf("context: %w", err)` for wrapping, never `_ =` to ignore errors - **Logging**: `log.Debugf` for record-level diagnostics, `log.Infof` for user-facing progress/status, `log.Warnf` for unexpected conditions. Extract methods should return errors, not log them. -- **Naming**: follow Go conventions — `Config` not `BrowserConfig`, `Extract` not `BrowsingData` +- **Naming**: follow Go conventions and the settled names in `rfcs/004-naming-decisions.md` — `Def` not `BrowserConfig`, `Extract` not `BrowsingData` - **Comment width**: wrap comments at 140 columns (matches `.golangci.yml` `lll.line-length`) -- **Tests**: use `t.TempDir()` for filesystem tests, `go-sqlmock` for database tests -- **Architecture**: see `rfcs/` for design documents +- **Tests**: use `t.TempDir()` with real fixture files (SQLite, JSON, LevelDB, plist) — never a live browser, never a database mock +- **Architecture**: see `rfcs/README.md` — design RFCs 000–012, format and technique RFCs 013–021 ## Key Constraints - `modernc.org/sqlite` pinned at v1.31.1 (v1.32+ requires Go 1.21) -- `golang.org/x/text` will be removed in refactoring (use 3-byte UTF-8 BOM instead) -- No `pkg/` + `internal/` directory structure — keep it simple -- No root-level library API — CLI calls `browser.DiscoverBrowsersWithKeys()` directly +- `tidwall/gjson` < v1.19, `golang.org/x/term` < v0.30, `golang.org/x/sys` at v0.30.0 — later releases raise their `go` directive above 1.20 +- New code goes under `internal/`, never `pkg/`; today's top-level packages move there phase by phase (`rfcs/012-migration-roadmap.md`), except `crypto/windows/` and `utils/injector`, which stay where they are +- No library API — `cmd/` is the only consumer of the packages below it diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b59a17f..06497fb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,9 +30,6 @@ golangci-lint run # Format gofumpt -l -w . goimports -w -local github.com/moond4rk/hackbrowserdata . - -# Spelling check -typos ``` ## Pull Requests diff --git a/cmd/hack-browser-data/flags_test.go b/cmd/hack-browser-data/flags_test.go new file mode 100644 index 0000000..97826c0 --- /dev/null +++ b/cmd/hack-browser-data/flags_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "flag" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var update = flag.Bool("update", false, "rewrite testdata/flags.golden from the current command tree") + +func TestFlagSurface(t *testing.T) { + golden := filepath.Join("testdata", "flags.golden") + got := flagSurface(rootCmd()) + if *update { + require.NoError(t, os.MkdirAll(filepath.Dir(golden), 0o755)) + require.NoError(t, os.WriteFile(golden, []byte(got), 0o644)) + } + want, err := os.ReadFile(golden) + require.NoError(t, err) + assert.Equal(t, string(want), got, "regenerate with: go test ./cmd/hack-browser-data -run TestFlagSurface -update") +} + +func flagSurface(root *cobra.Command) string { + var lines []string + for _, cmd := range sortedCommands(root) { + cmd.InitDefaultHelpFlag() + path := cmd.CommandPath() + for _, f := range sortedFlags(cmd.LocalFlags()) { + marker := "" + if cmd.PersistentFlags().Lookup(f.Name) == f { + marker = "persistent" + } + lines = append(lines, flagLine(path, f, marker)) + } + for _, f := range sortedFlags(cmd.InheritedFlags()) { + lines = append(lines, flagLine(path, f, "inherited")) + } + } + return strings.Join(lines, "\n") + "\n" +} + +func sortedCommands(root *cobra.Command) []*cobra.Command { + cmds := []*cobra.Command{root} + for i := 0; i < len(cmds); i++ { + cmds = append(cmds, cmds[i].Commands()...) + } + sort.Slice(cmds, func(i, j int) bool { return cmds[i].CommandPath() < cmds[j].CommandPath() }) + return cmds +} + +func sortedFlags(fs *pflag.FlagSet) []*pflag.Flag { + var flags []*pflag.Flag + fs.VisitAll(func(f *pflag.Flag) { flags = append(flags, f) }) + sort.Slice(flags, func(i, j int) bool { return flags[i].Name < flags[j].Name }) + return flags +} + +func flagLine(path string, f *pflag.Flag, marker string) string { + // Usage text is excluded: its wording may still be clarified, while name, shorthand, type and default are frozen. + fields := []string{path, "--" + f.Name} + if f.Shorthand != "" { + fields = append(fields, "-"+f.Shorthand) + } + fields = append(fields, f.Value.Type(), strconv.Quote(f.DefValue)) + if marker != "" { + fields = append(fields, marker) + } + return strings.Join(fields, " ") +} diff --git a/cmd/hack-browser-data/testdata/flags.golden b/cmd/hack-browser-data/testdata/flags.golden new file mode 100644 index 0000000..ff6803e --- /dev/null +++ b/cmd/hack-browser-data/testdata/flags.golden @@ -0,0 +1,43 @@ +hack-browser-data --browser -b string "all" +hack-browser-data --category -c string "all" +hack-browser-data --dir -d string "results" +hack-browser-data --format -f string "json" +hack-browser-data --help -h bool "false" +hack-browser-data --keychain-pw string "" +hack-browser-data --profile-path -p string "" +hack-browser-data --verbose -v bool "false" persistent +hack-browser-data --zip bool "false" +hack-browser-data archive --browser -b string "all" +hack-browser-data archive --category -c string "all" +hack-browser-data archive --help -h bool "false" +hack-browser-data archive --output -o string "browser-data.zip" +hack-browser-data archive --verbose -v bool "false" inherited +hack-browser-data dump --browser -b string "all" +hack-browser-data dump --category -c string "all" +hack-browser-data dump --dir -d string "results" +hack-browser-data dump --format -f string "json" +hack-browser-data dump --help -h bool "false" +hack-browser-data dump --keychain-pw string "" +hack-browser-data dump --profile-path -p string "" +hack-browser-data dump --zip bool "false" +hack-browser-data dump --verbose -v bool "false" inherited +hack-browser-data dumpkeys --browser -b string "all" +hack-browser-data dumpkeys --help -h bool "false" +hack-browser-data dumpkeys --keychain-pw string "" +hack-browser-data dumpkeys --output -o string "" +hack-browser-data dumpkeys --verbose -v bool "false" inherited +hack-browser-data list --detail bool "false" +hack-browser-data list --help -h bool "false" +hack-browser-data list --verbose -v bool "false" inherited +hack-browser-data restore --browser -b string "" +hack-browser-data restore --category -c string "all" +hack-browser-data restore --data-dir string "" +hack-browser-data restore --data-zip string "" +hack-browser-data restore --dir -d string "results" +hack-browser-data restore --format -f string "json" +hack-browser-data restore --help -h bool "false" +hack-browser-data restore --keys string "" +hack-browser-data restore --zip bool "false" +hack-browser-data restore --verbose -v bool "false" inherited +hack-browser-data version --help -h bool "false" +hack-browser-data version --verbose -v bool "false" inherited diff --git a/rfcs/000-goals-and-constraints.md b/rfcs/000-goals-and-constraints.md new file mode 100644 index 0000000..a115271 --- /dev/null +++ b/rfcs/000-goals-and-constraints.md @@ -0,0 +1,78 @@ +# RFC-000: Goals & Constraints + +## Context + +HackBrowserData extracts and decrypts local browser data (passwords, cookies, history, bookmarks, and related artifacts) from Chromium-based browsers, Firefox, and Safari across Windows, macOS, and Linux. It is MIT-licensed, widely used, and was presented at DEF CON. The current codebase works but carries years of incremental growth: + +- a `Browser` interface whose constructor discovers profiles and whose `Extract` does acquisition, key retrieval, decryption, and result assembly in one call, re-implemented per browser; +- per-OS `platformBrowsers()` lists of `types.BrowserConfig`, joined by key to a separate Windows `winutil.Table`, plus `ChromiumYandex` / `ChromiumOpera` kinds switched on across files; +- discovery, validation, and output concerns tangled into the command handlers (`-c` and `-f` are checked only after discovery and the keychain prompt). + +This is a ground-up redesign of the _structure_. The decryption and acquisition techniques are already published and are kept as-is behind stable package boundaries; what changes is how the program is assembled around them. + +## Goals + +1. **Reference-grade architecture.** A newcomer should be able to read `internal/app` top to bottom and understand the whole run. The pipeline is explicit, not emergent. +2. **Operator experience.** Usage errors fail before any browser is touched or any keychain prompt appears. Every browser/data-type pair yields a reported outcome. Secrets are retrieved only when the requested output needs them. Output is deterministic. +3. **Compatibility.** Nobody's command line, script, or output parser has to change (see the contract below). +4. **Code quality that lasts.** Adding a browser, a data type, or an output format is a single, documented, test-covered motion. No hidden coupling between stages. +5. **Showcase readiness.** The tree, the names, and the data flow are good enough to put on a slide. + +## Non-goals + +- **No new capability.** No new browsers beyond those already supported, no new bypasses, no new decryption techniques. The rewrite is organizational and qualitative. +- **No interface changes.** No renamed commands or flags, no new defaults, no new exit codes, no output schema changes. Additive, opt-in surface is allowed only where a DECIDED item calls for it ([RFC-009](009-cli-surface.md)). +- **No network features.** The tool stays fully offline. No telemetry, no update checks, no remote anything. +- **No GUI.** CLI only. +- **No public library API.** The module is consumed through its CLI. Everything below `cmd/` lives in `internal/` (see [RFC-002](002-package-layout.md)), except the ABE unit, whose move is DEFERRED; the module path does not change and there is no v2. + +## The compatibility contract (DECIDED) + +The rewrite is invisible from the outside. Every item below behaves exactly as in v1.1.0, and a compatibility test suite pins it ([RFC-011](011-testing-and-quality.md)). + +| Surface | Frozen as | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| Commands | `dump` (also the no-subcommand default, with its flags mirrored on the root), `dumpkeys`, `archive`, `restore`, `list`, `version` | +| Flags | every flag's name, shorthand, type, and default, on every command ([RFC-009](009-cli-surface.md)) | +| Default selection | `-b all`, `-c all`, `-f json`, `-d results` | +| Output files | one `.` per non-empty category (`password.csv`, `cookie.json`, …); `--zip` packs them into `/.zip` | +| Formats | `csv` (UTF-8 BOM), `json` (two-space indent, today's HTML escaping), `cookie-editor` | +| Fields | snake_case keys and columns, `browser` and `profile` first, then today's fields in today's order | +| Stamp values | `browser` = the display name (`Chrome`, `Microsoft Edge`); `profile` = today's profile name ([RFC-003](003-core-types.md)) | +| `keys.json` | dump version `"2"`, today's schema, readable by v1.1.0 | +| Archive | zip layout `/`, readable by v1.1.0 `restore` | +| Exit status | `0` when the run completes (including partial results and "no browsers found"); `1` when it cannot start or finish | + +Not part of the contract: log lines and the human-readable summary on stderr, and row order where today's order is unspecified or wrong. Output may change only for listed bug fixes where today's output is wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, and the `browser` value `restore` stamps ([RFC-008](008-output-and-export.md)); each is called out where it is fixed. + +## Hard constraints + +| Constraint | Reason | +| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Builds on **Go 1.20** | Windows 7 support. No `log/slog`, `slices`, `maps`, `cmp`, or any stdlib addition from 1.21+. | +| Dependency **pins** | `modernc.org/sqlite` v1.31.1, `tidwall/gjson` < v1.19, `golang.org/x/term` < v0.30, `golang.org/x/sys` at v0.30.0 — later releases raise their `go` directive above 1.20 ([RFC-010](010-dependencies.md)). | +| **Compatible interface** | The contract above. | +| **MIT** license | Project licensing; third-party license hygiene per [RFC-010](010-dependencies.md). | +| **Windows / macOS / Linux** | Existing supported matrix; no platform regressions. | +| Fully **offline** | Security tool run on evidence; it must not emit traffic. | + +## Guiding principles + +These are the invariants every later RFC is built on. + +- **One explicit pipeline.** A run is a fixed sequence of stages (see [RFC-001](001-architecture-and-pipeline.md)). Stages do not call back into each other; data flows one way. +- **Snapshot-first.** Acquisition copies the browser's files into a snapshot; every parser reads only from the snapshot, never from the live profile. Today's code already copies sources into a temp session before parsing; the rewrite turns that habit into a stage with its own contract ([RFC-007](007-snapshot-and-acquisition.md)). A dump captures one user data dir at a time and removes its copies before the next, so copied secrets never outlive the extractions that read them. +- **Lazy secrets.** Keys are retrieved, and the macOS login keychain is opened, on the first decrypt that needs them, not at discovery time. A run that only touches non-secret data never prompts — today `dump -b chrome -c history` on macOS still does. +- **Outcome per extraction.** Each extraction, one (user data dir, profile, data-type) unit, produces an outcome — `ok`, `partial`, `absent`, `unsupported`, or `error` — and the run reports all of them, together with any failure above an extraction, such as a user data dir that cannot be read. A single failure never aborts the rest. +- **Wire names follow Go names.** JSON keys and CSV columns are the snake_case form of the Go field names, enforced by lint. Because output is frozen, the record field names are frozen with it. (DECIDED) +- **`internal/` only.** No `pkg/`, no root-level library. The absence of an exported Go API frees the rewrite from Go-level compatibility; the CLI contract above is the only compatibility obligation. + +## What success looks like + +- `go build ./cmd/hack-browser-data/` on a clean Go 1.20 toolchain, cross-compiling to all three OSes. +- The same snapshot produces byte-identical output files on the old and the new code path, except for the listed bug fixes. +- Every command's flag set — names, shorthands, types, defaults — matches v1.1.0's, plus the additive `--keychain-pw-stdin`. +- A usage error (`-f bogus`) exits `1` before discovery and before any keychain prompt. +- A run with no decryptable targets still exits `0` and reports `absent`/`unsupported` honestly. +- Adding a plain Chromium fork touches the browser table and nothing structural. +- The dependency set is justified line-by-line in [RFC-010](010-dependencies.md). diff --git a/rfcs/001-architecture-and-pipeline.md b/rfcs/001-architecture-and-pipeline.md new file mode 100644 index 0000000..a47f3fe --- /dev/null +++ b/rfcs/001-architecture-and-pipeline.md @@ -0,0 +1,125 @@ +# RFC-001: Architecture & Pipeline + +## The shape of a run + +A run is a one-way pipeline of seven stages. Each stage takes the previous stage's output and produces the next stage's input. No stage reaches backward. The orchestration lives in `internal/app`; the stages themselves are implemented by the packages named below. + +``` + ┌───────────┐ + argv ───▶ │ Validate │ flags → app.Request; no browser files touched, nothing created + └─────┬─────┘ + ▼ + ┌───────────┐ + │ Discover │ which user data dirs and profiles exist on this machine + └─────┬─────┘ + ▼ + ┌───────────┐ + │ Plan │ user data dirs × profiles × requested categories + └─────┬─────┘ → Extractions (+ Skipped, with reasons) + the union of files + ▼ + ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ Execute, once per user data dir ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ + ┌───────────┐ + │ Capture │ copy the user data dir's planned files into a temporary snapshot + └─────┬─────┘ + ▼ + ┌───────────┐ + │ Extract │ parse snapshot files → records; secrets fetched lazily + └─────┬─────┘ (first decrypt in a key scope triggers retrieval) + ▼ + ┌───────────┐ + │ Export │ append each extraction's records to today's files, + └─────┬─────┘ then remove the snapshot and take the next user data dir + ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ + ▼ + ┌───────────┐ + │ Report │ every result → summary on stderr + └───────────┘ +``` + +## Stage contracts + +### 1. Validate + +Turns parsed flags into a typed `app.Request`: which categories, which browser, the `-p` override, output directory, format, `--zip`, and how the keychain password is supplied. Rejects bad input here — an unknown format, category, or browser ID, or an output directory that cannot be created, fails now with exit status `1` (today's status), **before** any browser is discovered and **before** any keychain prompt. Today `-c` and `-f` are checked only after discovery and the prompt; that ordering bug is designed out here. + +Validate touches no browser files and creates nothing: the output-directory check only confirms that `-d` is a directory or that its nearest existing ancestor is a writable directory. For `restore`, reading `--keys` is part of Validate, because `-b` there is checked against the dump's vaults ([RFC-009](009-cli-surface.md)). `-p` combined with `-b all` logs a warning and is ignored, as today, instead of being dropped silently. + +**In:** parsed flags. **Out:** a validated `app.Request`. **Owner:** `cmd/hack-browser-data` (flag wiring) + `app.Validate` (rules). + +### 2. Discover + +Enumerates which supported browsers are present and which profiles each one has, on this OS. Produces `browser.UserDataDir` values — one per data directory found, so two Arc packages are two user data dirs — each holding its `Profile` list. Discovery is read-only metadata work: it stats files and directories; it does not open databases or touch secrets. The one exception is Safari, which lists its named profiles only inside `SafariTabs.db`: its Discover captures that single file into a temporary snapshot and reads the copy, never the live database ([RFC-005](005-browser-definitions.md)). A user data dir that exists but cannot be read is not dropped: it comes back as an `error` result for that browser ([RFC-005](005-browser-definitions.md)). + +**In:** `app.Request` + `browser.Supported()`, this OS's rows. **Out:** an `app.Discovery` — the user data dirs found, plus the failures. **Owner:** `app.Discover`, which dispatches on `Def.Base` to `internal/browser/{chromium,firefox,safari}`. + +### 3. Plan + +The cross product. For each user data dir, each profile, and each requested category, the profile's `Extractors` say whether the category is supported and which source files it needs. Plan turns that into a flat list of `Extraction`s, a `Skipped` list with a reason for every requested pair that can't run (`unsupported` by this browser, `absent` on disk) plus Discover's failures, and the union of files to capture, deduplicated by user data dir and path — so a file two categories share (Chromium `History` feeds both history and downloads) is copied once, where today it is copied twice. Plan only stats files; it opens nothing. A `Plan` is plain data, with no functions inside, so `list` prints it and tests compare it. + +**In:** an `app.Discovery` + `app.Request`. **Out:** `app.Plan{Dirs, Files, Extractions, Skipped}`. **Owner:** `app.NewPlan`. + +### 4–6. Capture, Extract, Export — once per user data dir + +`app.Execute` runs the next three stages one user data dir at a time. It captures the dir's files into a temporary snapshot, runs the dir's extractions — each extraction's records go to Export as it finishes — and removes the snapshot before it captures the next dir. At most one user data dir's copies of `Login Data`, `Cookies`, and the like are on disk at once, close to today's per-profile session; a run-long snapshot directory would keep every browser's copies until the end, and peak disk use would be all of them together. `archive` is the one exception: it captures every user data dir into one snapshot directory, because the zip of that directory is what it produces ([RFC-007](007-snapshot-and-acquisition.md)). + +#### 4. Capture + +Copies the user data dir's planned files into its snapshot, a subdirectory named by the dir's ID ([RFC-007](007-snapshot-and-acquisition.md)). After Capture, the live browser profile is never read again. Capture owns the awkward realities of reading files a running browser holds open — the Windows locked-file fallback, SQLite `-wal`/`-shm` sidecars, LevelDB lock files — so every parser downstream reads plain, stable files. Capture keeps going when a file fails: a file that vanished since Plan turns its extraction into `absent`, one that failed to copy turns its extraction into `error`, and every other extraction runs. + +**In:** the user data dir's share of `Plan.Files`. **Out:** the dir's `snapshot.Snapshot`, inside a `snapshot.Dir`. **Owner:** `internal/snapshot`. + +#### 5. Extract + +For each extraction, open its source files _from the snapshot_ and parse them into records. Secrets are lazy: each is retrieved once per key scope, by the first record that needs it — the user data dir for Chromium (`ProfileSnapshot.MasterKeys`), the profile for Firefox, the run for the macOS login keychain ([RFC-006](006-key-retrieval-and-crypto.md)); later extractions in the same scope reuse it. A run that only asked for bookmarks and history never retrieves a key, never opens the keychain, and never prompts. + +A record whose secret can't be recovered is still emitted with that field empty (today's output) and reported as a record-level problem, which makes the extraction `partial`. + +**In:** the user data dir's extractions + its snapshot. **Out:** records and record-level problems, through a `browser.Collector`. **Owner:** `internal/browser/*` extractors + `internal/masterkey` + `internal/keychain` + `internal/crypto`. + +#### 6. Export + +Appends each extraction's records, as it finishes, to today's files in today's formats ([RFC-008](008-output-and-export.md)): one file per non-empty category, field names frozen, rows in a deterministic order defined once per category. + +**In:** records + `app.Request`. **Out:** files on disk (and the `--zip` archive). **Owner:** `internal/export`. + +### 7. Report + +Collects every result — each extraction's, and each failure that concerns a whole browser or user data dir — and prints a summary on stderr. The summary is additive: it is not part of the compatibility contract, and it never changes the exit status. + +**In:** an `app.Summary`. **Out:** the summary. **Owner:** `app.Report`. + +## The outcome model + +Every extraction resolves to exactly one outcome. This is the single most important quality lever in the design: it replaces "an error was logged somewhere" with "the run completed and told you precisely what it got." + +| Outcome | Meaning | Example | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | +| `ok` | Ran with no record-level problems. A source with no rows is `ok` with zero records, not `absent`. | 224 cookies decrypted. | +| `partial` | Ran and emitted records, but reported record-level problems — a secret that could not be recovered, a row that could not be parsed. | 224 cookies, 4 with an empty value. | +| `absent` | Supported, but a required source wasn't on disk, or none of its optional ones was. | Browser installed, no `Login Data` file. | +| `unsupported` | This browser can't produce this category. | Firefox credit cards. | +| `error` | Failed as a whole: the extractor returned an error, a source failed to copy, or problems were reported and no record could be emitted. | Snapshot copy failed. | + +`partial` is first-class, not an afterthought: a few undecryptable rows are normal in the field and must not look like total failure. + +A failure that concerns a whole browser or user data dir rather than one extraction — Discover could not read it, key retrieval failed — is reported once, as an `error` result that names only the user data dir. The extractions it touches still get their own outcomes: after a failed key retrieval, passwords and cookies are still emitted with their encrypted fields empty, so those extractions end `partial`. + +## Exit status (compatibility contract) + +| Status | Meaning | +| ------ | ------------------------------------------------------------------------------------------------------------ | +| `0` | The run completed. Every result — including `partial`, `error`, and "no browsers found" — is in the summary. | +| `1` | The run could not start or finish: a usage error, an unreadable `--keys`, an output write failure. | + +This is today's behavior and stays frozen. `absent` and `unsupported` are not failures — asking all browsers for all categories and getting honest "not here" answers is a successful run. Finer exit codes (separate usage and partial statuses) are DEFERRED; if ever added, they must be opt-in. + +## Why a pipeline and not the current interface + +Today each browser package re-implements the orchestration: Chromium, Firefox, and Safari each copy files into a session, switch on the requested categories, and assemble results inside `Extract`, and per-fork special cases (`p.kind == types.ChromiumYandex`) sit inside the Chromium switch. Bugs live where nothing else checks them: Firefox sorts history ascending while the other browsers sort descending, and the archive keys files by browser key alone (`browser/archive.go`, `WriteArchive`), so the second Arc user data dir is dropped. + +Splitting the run into named stages means: + +- Each concern is implemented and tested **once**, not per browser. +- A browser contributes only what is browser-specific: where its files are (Discover) and how to parse them (Extract). Everything else is shared machinery. +- The `Plan` is a value you can print, which is all `list` is. +- Failures are localized to an extraction and reported, never fatal to the run. diff --git a/rfcs/001-project-architecture.md b/rfcs/001-project-architecture.md deleted file mode 100644 index a3ba433..0000000 --- a/rfcs/001-project-architecture.md +++ /dev/null @@ -1,177 +0,0 @@ -# RFC-001: Project Architecture & Data Model - -**Author**: moonD4rk -**Status**: Living Document -**Created**: 2026-04-05 - -## 1. Project Positioning - -HackBrowserData is a CLI security research tool that extracts and decrypts browser data from Chromium-based browsers and Firefox across Windows, macOS, and Linux. - -Key constraints: - -- **Go 1.20** — the module must build with Go 1.20 to maintain Windows 7 support. Features from Go 1.21+ (`log/slog`, `slices`, `maps`, `cmp`) must not be used. -- **Supported engines**: Chromium (including Yandex and Opera variants), Firefox, and Safari. -- **Supported platforms**: Windows (DPAPI), macOS (Keychain), Linux (D-Bus Secret Service). -- **No root-level library API** — the CLI calls `browser.DiscoverBrowsersWithKeys()` directly; there is no importable `pkg/` surface. - -## 2. Directory Structure - -``` -HackBrowserData/ -├── cmd/hack-browser-data/ # CLI entrypoint: cobra root, dump, dumpkeys, archive, restore, list, version -├── browser/ # Browser interface, DiscoverBrowsersWithKeys(), platform browser lists -│ ├── chromium/ # Chromium engine: extraction, decryption, profile discovery -│ ├── firefox/ # Firefox engine: extraction, NSS key derivation -│ └── safari/ # Safari engine: Keychain, Bookmark, History, Downloads (macOS only) -├── types/ # Data model: Category enum, Entry structs, BrowserData -├── crypto/ # Encryption primitives, cipher version detection -├── masterkey/ # Platform-specific master key retrieval (Keychain/DPAPI/D-Bus) -├── filemanager/ # Temp file session, locked file handling (Windows) -├── output/ # Output Writer: CSV, JSON, CookieEditor formatters -├── log/ # Logging with level filtering -└── utils/ # SQLite query helpers, file utilities -``` - -## 3. Core Data Model - -### 3.1 Category - -`Category` is an `int` enum representing 9 browser-agnostic data kinds: Password, Cookie, Bookmark, History, Download, CreditCard, Extension, LocalStorage, SessionStorage. - -Three categories are classified as **sensitive** (Password, Cookie, CreditCard) via `IsSensitive()`, enabling safe-by-default export scenarios. - -### 3.2 Entry Types - -Each category has a corresponding Entry struct with `json` and `csv` struct tags. All structs are flat (no nesting) and use `time.Time` for timestamps. - -| Struct | Category | Key Fields | -|--------|----------|------------| -| `LoginEntry` | Password | URL, Username, Password, CreatedAt | -| `CookieEntry` | Cookie | Host, Path, Name, Value, IsSecure, IsHTTPOnly, ExpireAt, CreatedAt | -| `BookmarkEntry` | Bookmark | Name, URL, Folder, CreatedAt | -| `HistoryEntry` | History | URL, Title, VisitCount, LastVisit | -| `DownloadEntry` | Download | URL, TargetPath, TotalBytes, StartTime, EndTime | -| `CreditCardEntry` | CreditCard | Name, Number, ExpMonth, ExpYear | -| `ExtensionEntry` | Extension | Name, ID, Description, Version | -| `StorageEntry` | LocalStorage, SessionStorage | URL, Key, Value | - -`StorageEntry` is shared by both LocalStorage and SessionStorage. - -### 3.3 BrowserData Container - -`BrowserData` is the per-profile data container holding typed slices — one per category, populated field-by-field during extraction. `Extract()` returns `[]ExtractResult`, where each element pairs a `Profile` identity with a `*BrowserData`. The output layer uses `makeExtractor[T]()` generics to pull the correct slice for serialization. - -## 4. Browser Interface & Registration - -### 4.1 BrowserKind - -Each config declares an engine kind that determines source paths and extraction logic. Kinds fall into three engine families: - -- **Chromium** (`Chromium`, `ChromiumYandex`, `ChromiumOpera`) — the standard Chromium layout plus two variants that override file names or storage paths for Yandex and Opera forks. See RFC-003. -- **Firefox** — NSS-based key derivation from `key4.db`, SQLite + JSON source files. See RFC-005. -- **Safari** — macOS only, with direct Keychain-based credential extraction. See RFC-006 §7. - -See `types/category.go` for the authoritative enum definition. - -### 4.2 BrowserConfig - -`BrowserConfig` is the declarative, platform-specific browser definition containing: Key (CLI matching; also the Windows ABE / winutil.Table identifier when WindowsABE is true), Name (display), Kind (engine), KeychainLabel (macOS Keychain / Linux D-Bus Secret Service label), WindowsABE (bool — enable Windows App-Bound Encryption v20 path), UserDataDir (data path). - -### 4.3 Browser Selection Flow - -There are two entry points, one for extraction and one for discovery: - -``` -DiscoverBrowsersWithKeys(opts) // used by `dump` — ready to Extract - → discoverFromConfigs(configs, opts) // shared discovery core - → platformBrowsers() // build-tagged list for this OS - → filter by name / profile path - → newBrowser(cfg) // dispatch to chromium/firefox/safari.NewBrowser - → discoverProfiles() // scan profile subdirectories - → resolveSourcePaths() // stat candidates, first match wins - → newCredentialInjector(opts) // build-tagged: returns a browserInjector - → for each browser: // closure captures retriever + keychain pw lazily - inject(b) // type-assert KeyManager / KeychainPasswordReceiver - -DiscoverBrowsers(opts) // used by `list` / `list --detail` - → discoverFromConfigs(configs, opts) // same shared discovery core, NO injection -``` - -`DiscoverBrowsersWithKeys` does discovery + decryption setup in one call; the returned browsers are ready for `b.Extract`. `DiscoverBrowsers` skips injection entirely, so list-style commands never trigger the macOS Keychain password prompt — they have no use for the credential. Both entry points share the same `discoverFromConfigs` core, so filtering/profile-path/glob semantics stay consistent. - -Key design decisions: - -- **One Retriever chain per process** — built lazily inside `newCredentialInjector` and reused across every Chromium browser and every profile to prevent repeated keychain prompts on macOS. -- **Discovery is decoupled from injection** — `discoverFromConfigs` is injection-free; `DiscoverBrowsers` stops after it, `DiscoverBrowsersWithKeys` continues into injection. -- **Profile discovery differs by engine**: Chromium looks for `Preferences` files in subdirectories; Firefox accepts any subdirectory containing known source files. -- **Flat layout fallback** — Opera-style browsers that store data directly in UserDataDir (no profile subdirectories) are handled by falling back to the base directory. - -### 4.4 Platform Browser Lists - -Browser configs are defined per-platform via build tags in `platformBrowsers()` (`browser/browser_{darwin,linux,windows}.go`). The supported set groups by engine family: - -- **Chromium-based** — the largest family, covering mainstream browsers (Chrome, Edge, Brave, Vivaldi, Opera, Chromium) across all three platforms plus regional variants and forks. Windows carries the longest list because of China-region Chromium forks (360, QQ, Sogou, DC, …) and MSIX-packaged browsers with dynamic install paths (Arc, DuckDuckGo). -- **Firefox** — all three platforms, via internal NSS key derivation (RFC-005). -- **Safari** — macOS only, via direct Keychain `InternetPassword` extraction (RFC-006 §7). - -Adding a new browser is a config-only change in `platformBrowsers()`; this section does not need updates for new variants within an existing family. - -## 5. Extract() Orchestration - -Both Chromium and Firefox engines follow the same per-profile extraction pattern (Firefox runs it inside each `profile.extract()` call; for Firefox the master key comes from `key4.db` rather than a platform API): - -``` -Extract(categories) // per-profile: one invocation per profile - 1. NewSession() → create isolated temp directory - 2. acquireFiles(session) → copy source files to temp dir (with dedup and WAL/SHM) - 3. getMasterKey(session) → platform-specific key retrieval (Firefox: key4.db) - 4. for each category: - extractCategory(data, cat, masterKey, path) - 5. defer session.Cleanup() → remove temp directory -``` - -For details on file acquisition, see [RFC-008](008-file-acquisition-and-platform-quirks.md). For encryption details, see [RFC-003](003-chromium-encryption.md) (Chromium) and [RFC-005](005-firefox-encryption.md) (Firefox). For key retrieval, see [RFC-006](006-key-retrieval-mechanisms.md). - -### 5.1 Collect-and-Continue Pattern - -The extraction loop maximizes data recovery. Each category is extracted independently — a failure in one does not affect others. Errors are handled at three levels: - -| Level | Trigger | Action | -|-------|---------|--------| -| **Session failure** | Temp dir cannot be created | Abort entirely, return error | -| **Category failure** | Source file missing or extraction error | Skip category, continue to next | -| **Record failure** | Single row decryption fails | Skip record, continue extraction | - -**Master key failure is non-fatal.** If the key cannot be retrieved, categories requiring decryption (passwords, cookies, credit cards) produce empty values, while non-encrypted categories (history, bookmarks, downloads) still succeed. - -### 5.2 Custom Extractors - -The `categoryExtractor` interface allows browser-specific extraction logic. Yandex uses custom extractors for passwords and credit cards; Opera uses a custom extractor for extensions. All other categories fall through to the default Chromium implementation. - -## 6. Dependency Constraints - -The module is pinned to `go 1.20` in `go.mod`. This is enforced by a CI lint check that fails if the directive changes. - -| Dependency | Version | Purpose | -|-----------|---------|---------| -| `modernc.org/sqlite` | v1.31.1 (pinned) | Pure-Go SQLite. v1.32+ requires Go 1.21 | -| `github.com/syndtr/goleveldb` | v1.0.0 | LevelDB for Chromium localStorage/sessionStorage | -| `github.com/tidwall/gjson` | v1.18.0 | JSON path queries | -| `github.com/spf13/cobra` | v1.10.2 | CLI framework | -| `github.com/moond4rk/keychainbreaker` | v0.2.5 | macOS keychain decryption | -| `github.com/godbus/dbus/v5` | v5.2.2 | Linux D-Bus Secret Service | -| `golang.org/x/sys` | v0.30.0 | Windows syscalls (DPAPI, DuplicateHandle) | - -## Related RFCs - -| RFC | Topic | -|-----|-------| -| [RFC-002](002-chromium-data-storage.md) | Chromium data file locations and storage formats | -| [RFC-003](003-chromium-encryption.md) | Chromium encryption mechanisms per platform | -| [RFC-004](004-firefox-data-storage.md) | Firefox data file locations and storage formats | -| [RFC-005](005-firefox-encryption.md) | Firefox NSS encryption and key derivation | -| [RFC-006](006-key-retrieval-mechanisms.md) | Platform-specific master key retrieval | -| [RFC-007](007-cli-and-output-design.md) | CLI commands and output formats | -| [RFC-008](008-file-acquisition-and-platform-quirks.md) | File acquisition and platform quirks | -| [RFC-009](009-windows-locked-file-bypass.md) | Windows locked file bypass technique | diff --git a/rfcs/002-package-layout.md b/rfcs/002-package-layout.md new file mode 100644 index 0000000..2d80c3e --- /dev/null +++ b/rfcs/002-package-layout.md @@ -0,0 +1,80 @@ +# RFC-002: Package Layout + +## The tree + +Everything except the command entrypoint lives under `internal/`. The entrypoint stays thin — the frozen cobra command tree and a call into `app`. + +``` +cmd/hack-browser-data/ main; cobra commands and flags (the frozen CLI surface); flags → app.Request +internal/ + app/ Validate, Discover, NewPlan, Execute, Report; dispatches on browser.Base to the base packages + browser/ Def, Base, Platform (Supported, Lookup); UserDataDir, DirID, Profile, DiscoverOptions; + Source, Extractor, ProfileSnapshot, Collector + chromium/ Chromium discovery, extractors, key input, archive sources, per-fork overrides (Yandex, Opera family) + firefox/ Firefox discovery, extractors, per-profile key derivation + safari/ Safari discovery and extractors + category/ Category: the data categories (the -c values and the output file names) + record/ record types (Login, Cookie, …), the sealed Record, Stamp; field names frozen by the output contract + masterkey/ Chromium key Set, Retriever, RetrieveAll, keys.json Dump; OS secret stores by build tag + crypto/ pure decrypt primitives over bytes (AES-CBC/GCM, 3DES, PBKDF2, ASN.1 PBE) + snapshot/ snapshot Dir and Snapshot, Capture, manifest, zip transport, the copier + export/ Writer; csv / json / cookie-editor encoders; --zip packaging + sqlitex/ thin modernc.org/sqlite helpers (open read-only by path, query) + timeconv/ browser epoch conversions (Chromium/WebKit, Unix, Firefox, Core Data) + winapi/ Windows only: syscall wrappers, DPAPI, locked-file copy, executable lookup + abe/ Windows only: App-Bound Encryption bridge — move DEFERRED, see below + keychain/ macOS only: the user's login keychain — one handle per run, opened on first use + log/ leveled logging (Debugf/Infof/Warnf) +``` + +The technique internals (the ABE payload, reflective injection, DPAPI and keychain specifics) sit behind `masterkey`, `keychain`, `winapi`, and the ABE unit by build tag. Their _mechanics_ are documented in the format and technique RFCs (013–021) and are out of scope for the design RFCs — here they are just packages with a contract ([RFC-006](006-key-retrieval-and-crypto.md)). + +**The ABE unit stays where it is (DEFERRED).** Today's `crypto/windows/` — the first-party C sources, the generated `bootstrap` layout package, and the `payload` package that embeds the built `.bin` — and `utils/injector` keep their paths in this rewrite, and so do `Makefile.frag`, `make payload`, and `make gen-layout`. Moving them changes the payload build, which needs its own validation on Windows, so only their importers change here. When the unit moves to `internal/abe/`, it moves as one: `//go:embed` only reaches files in the embedding package's directory or below, so the Makefile writes the payload there ([RFC-012](012-migration-roadmap.md)). + +## Dependency direction + +Dependencies point downward and are listed exhaustively; anything not listed is forbidden. + +| Package | May import (project-internal) | +| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | +| `cmd/hack-browser-data` | `app`, plus `browser` and `category` for help-text vocabulary (`-b` IDs, `-c` categories), `log` | +| `app` | every package below | +| `browser/chromium`, `browser/firefox`, `browser/safari` | `browser`, `category`, `record`, `masterkey`, `crypto`, `snapshot`, `sqlitex`, `timeconv`, `log` | +| `export` | `category`, `record`, `log` | +| `browser` | `category`, `record`, `masterkey`, `snapshot` | +| `masterkey` | `crypto`, `winapi`, `abe`, `keychain`, `log` | +| `snapshot` | `winapi`, `log` | +| `abe` | `winapi`, `log` | +| `record` | `category` | +| `sqlitex`, `winapi` | `log` | +| `category`, `crypto`, `timeconv`, `keychain`, `log` | nothing | + +`abe` stands for the ABE unit — `utils/injector` and `crypto/windows/payload` — until it moves. + +Four rules keep the graph acyclic and its seams honest: + +- **The base dispatch lives in `app`.** The base packages import `browser` for `Def`, `UserDataDir`, and `Extractor`, so `browser` cannot call them back; `app` switches on `Def.Base`. Init-time self-registration is ruled out by the `gochecknoinits` linter, and an explicit switch reads better on stage anyway. +- **`snapshot` speaks strings.** A `snapshot.File` names its user data dir by ID (`DirID`, a plain string) and its path relative to that directory; it never holds a `browser.UserDataDir`, because `browser.ProfileSnapshot` holds a `snapshot.Snapshot`. +- **`crypto` takes bytes.** Primitives receive raw keys and blobs; they never see a `masterkey.Set`, because `masterkey` is the package that calls them. +- **Interfaces live with their consumer.** `browser` declares the `Collector` its extractors use, and `app` implements it; `masterkey` and `browser/safari` each declare the one-method `LoginKeychain` they read. Constructors elsewhere return concrete types (`*snapshot.Dir`, `*export.Writer`). + +Review keeps the table, not a tool: a change that needs an edge the table does not list — say, `crypto` importing `browser` — updates the table first, in the same pull request. + +## Why `internal/` and nothing else (DECIDED) + +The current tree keeps packages at the module root (`browser/`, `crypto/`, `filemanager/`, `log/`, `masterkey/`, `output/`, `types/`, `utils/...`) and the project CLAUDE.md says "no `pkg/` + `internal/`." This RFC reverses that single decision, for the rewrite only, and keeps the "keep it simple" spirit by using `internal/` _instead of_ a split, not in addition to one. + +Reasons: + +1. **No Go-API burden.** Anything importable by path becomes a de-facto public API that external users pin to. HBD has no intended library consumers — it is a CLI. `internal/` makes that explicit and compiler-enforced, so we can rename and reshape freely across the whole rewrite. The CLI contract ([RFC-000](000-goals-and-constraints.md)) is the only compatibility obligation, and it is unaffected. +2. **A clear seam.** `cmd/` is the only thing outside `internal/`. The boundary between "the program's entrypoint" and "the program" is visible in the tree. +3. **It is still flat.** We are not introducing `pkg/` as well. There is exactly one home for library code, and it is `internal/`. + +Trade-off accepted: the module stops being importable as a library. The module path stays `github.com/moond4rk/hackbrowserdata` and releases continue as v1.x; there is no v2 (DECIDED). + +## Package sizing and naming rules + +- A package exists because it owns a _concept_, not because a file got long. `timeconv` and `category` are tiny on purpose. A package with nothing to own is not created — there is no `cli` (flags belong to `cmd`, rules to `app`) and no `textenc` (the CSV BOM is three bytes in `export`). +- A concept with per-OS implementations lives in one package with `_windows.go` / `_darwin.go` / `_linux.go` files; callers import one package and get the right implementation at build time. A concept that exists on only one OS — the locked-file copy, the ABE bridge, the macOS login keychain — lives in its own package whose files are all built for that OS: `winapi`, `abe`, and `keychain`. +- `winapi`, not `platform/windows`: a package named `windows` would collide with `golang.org/x/sys/windows`, which it imports, so every file would need an alias. `log` and `crypto` keep today's names although the standard library has packages of the same names: both are internal, and no file needs both. +- No `utils` grab-bag. The old tree is redistributed to named homes: `utils/sqliteutil` → `sqlitex`; `utils/fileutil` and `filemanager` → `snapshot` (copy, zip transport) and `export` (`--zip`); `utils/{winapi,winutil}` → `winapi`; `utils/injector` and `crypto/windows/` stay in place (the `abe` move is DEFERRED); `types` → `category`, `record`, and `browser`; `output` → `export`; `log` → `internal/log`. diff --git a/rfcs/003-core-types.md b/rfcs/003-core-types.md new file mode 100644 index 0000000..5ece123 --- /dev/null +++ b/rfcs/003-core-types.md @@ -0,0 +1,367 @@ +# RFC-003: Core Types + +This RFC fixes the shape of the central types; their names and the alternatives behind them are in [RFC-004](004-naming-decisions.md). Go 1.20 — no generics-stdlib helpers, but ordinary type parameters are available and used sparingly where they remove real duplication. + +Two rules apply to every type below: + +- **Interfaces live with their consumer; constructors return concrete types.** `browser` declares the `Collector` its extractors use, and `app` implements it. `snapshot.Temp` returns a `*snapshot.Dir`, `export.NewWriter` a `*export.Writer`, and `browser.NewProfileSnapshot` a `ProfileSnapshot`, not interfaces. +- **An enum's zero value is its default or "none", never a real non-default choice.** `category.Category`, `browser.Base`, and `app.Outcome` start at 1, so a forgotten field never reads as `Password` or `OutcomeOK`. `export.Format`'s zero is `JSON`, the `-f` default. `masterkey.Version` is a string whose zero is `""`. + +## Discovery types — `internal/browser` + +```go +// DiscoverOptions is what discovery is handed: everything it would otherwise read from the environment. +type DiscoverOptions struct { + Home string // the user's home directory, resolved once by app; tests pass a temp dir + ProfilePath string // the -p value, already validated; "" when not given (RFC-009) +} + +// DirID names one user data dir: Def.ID for the first one of a Def, then "-2", "-3"… appended for further +// ones, in Path order. It is its own type so that it cannot be passed where a Def.ID belongs. +type DirID string + +// UserDataDir is one browser data directory found on this machine: Chromium's "User Data", +// Firefox's Profiles directory, Safari's data under ~/Library. +type UserDataDir struct { + ID DirID // "chrome", "arc", "arc-2" — also the snapshot and archive directory name + Def Def // which browser it belongs to (RFC-005) + Path string // absolute path; every Source path resolves under it + Profiles []Profile +} + +// Profile is one profile within a user data dir. +type Profile struct { + Name string // the output's `profile` value (see below) + Dir string // relative to UserDataDir.Path; "" when the user data dir itself is the profile (flat layout) +} +``` + +`UserDataDir` is Chromium's own term (`--user-data-dir`): the directory holding `Local State` and the profile directories, as opposed to the program installation that holds the executable. HBD uses it for every base's data root — the directory a base's sources resolve under — even where the browser has no such word: Firefox's `Profiles` directory, and Safari's `~/Library` (below). A machine can have several for one browser — Arc's two MSIX packages on Windows each have one — and `restore` works on a copied one that was never installed here, which is why the type is not called `Installation` ([RFC-004](004-naming-decisions.md)). + +Two IDs sit side by side and must not be confused: `dir.ID` (`arc-2`) names the directory, `dir.Def.ID` (`arc`) names the browser. The `-b` value, a `keys.json` vault's `browser` key, and the per-fork overrides use `Def.ID`; the snapshot and archive layout use the `DirID`. On a machine with one Arc the two are equal, so a mix-up would pass every test there — the separate type makes it a compile error instead. + +`Profile.Name` is frozen by the output contract ([RFC-000](000-goals-and-constraints.md)): for Chromium the directory's base name (`Default`, `Profile 1` — what Chromium's `Profile::GetBaseName()` returns, not the display name `Local State` keeps in `profile.info_cache`); for Firefox the directory name (`97nszz88.default-release`); for Safari, `default` or the named profile's title (deduplicated with a `-N` suffix, the UUID when untitled). It is never a path. + +Safari has no single data directory — History lives under `~/Library/Safari`, cookies under `~/Library/Containers/com.apple.Safari/…` or `~/Library/Cookies` — so its user data dir is `~/Library`, the nearest common ancestor. + +## Extractor contract — `internal/browser` + +```go +// Source is one file or directory an extractor needs. +type Source struct { + Paths []string // candidates in priority order, relative to the profile dir — or to the user data dir when Shared + IsDir bool // a directory (LevelDB, Session Storage), copied whole + Shared bool // belongs to the whole user data dir, not one profile: Local State + Optional bool // the extraction still runs without it +} + +// Extractor declares the sources a category needs and how to parse them. +type Extractor struct { + Sources []Source + Extract func(ctx context.Context, ps ProfileSnapshot, out Collector) error +} + +// Extractors maps each category a profile supports to its extractor. +type Extractors map[category.Category]Extractor +``` + +Sources are static data: a base package declares them once per category and never rewrites them per profile. Plan joins a profile-scoped path with the profile's `Dir`, leaves a `Shared` one as it is, and captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it. + +An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none is there. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces today's output, including a profile that only ever synced passwords, without a special case. + +`Extractor` / `Extractors` are **DECIDED**. + +### ProfileSnapshot and Collector + +```go +// ProfileSnapshot is what an extractor is handed for one extraction: its profile's view of the user data dir's +// snapshot, and the dir's keys. +type ProfileSnapshot struct { + Profile Profile // the extraction's profile; profile-scoped sources resolve under its Dir + snap snapshot.Snapshot + masterKeys func(ctx context.Context) masterkey.Set +} + +// NewProfileSnapshot is how app hands a profile its share; tests pass a fixture Snapshot and a fake masterKeys. +func NewProfileSnapshot(snap snapshot.Snapshot, p Profile, masterKeys func(context.Context) masterkey.Set) ProfileSnapshot + +// Path returns the captured path of src: its first candidate present in the snapshot. A candidate that was +// never captured is skipped; one whose copy failed returns that copy's error. +func (ps ProfileSnapshot) Path(src Source) (string, error) + +// MasterKeys returns the user data dir's Chromium keys, one per version. The first call in a dir retrieves them and +// later calls reuse the result; a version that could not be retrieved is absent from the Set. +func (ps ProfileSnapshot) MasterKeys(ctx context.Context) masterkey.Set + +// Collector receives one extraction's output. It stamps Browser and Profile on every record, so no extractor can omit +// them. +type Collector interface { + Add(r record.Record) // one parsed record + Fail(err error) // one record-level problem: a secret that could not be recovered, or a row dropped as unparseable +} +``` + +An extractor reads from its `Source`s and hands its records to the `Collector`. It emits records as it reads them; it does not accumulate slices. A record whose secret can't be recovered is emitted anyway with that field empty — today's output — and reported through `Fail`, which records the problem and lets the extraction continue, like `testing.T.Error`; the extraction ends `partial`. An extractor never logs errors: it returns extraction-level errors and reports record-level ones. Base-specific context an extractor needs (Safari's profile UUID for filtering downloads and the run's login keychain, the Yandex override) is captured when the base package builds the profile's `Extractors`, not passed through the `ProfileSnapshot`. + +`MasterKeys` takes a context because its first call may block — on a secret-store lookup, or on macOS on the login keychain's no-echo password prompt — and Ctrl-C cancels the run's context ([RFC-009](009-cli-surface.md)). It returns no error: the dir's call-once in `app` keeps the retrieval error and reports it once, as the user data dir's `error` result ([RFC-001](001-architecture-and-pipeline.md)), and a record whose key is missing is emitted with that field empty and reported through `Fail`. Every `ProfileSnapshot` of one user data dir shares that call-once; `masterKeys` is nil for Firefox and Safari, whose extractors never call it. + +There is no separate `Secrets` handle ([RFC-004](004-naming-decisions.md)), and the login password is not on `ProfileSnapshot` at all: it opens one resource, the login keychain, and that resource is what gets handed out (below). + +## Pipeline values — `internal/app` + +```go +// Extraction is one unit of work: one category of data from one profile of one user data dir. It is pure data — +// the extractor is looked up when it runs — so a Plan prints as it is and compares with reflect.DeepEqual in tests. +type Extraction struct { + DirID browser.DirID // which user data dir + Profile string // Profile.Name; "" in a result about a whole browser or user data dir + Category category.Category // zero in a result about a whole browser or user data dir +} + +// Discovery is what Discover found: the user data dirs, plus an error result for each browser whose data could +// not be read — reported, never mistaken for absence. +type Discovery struct { + Dirs []browser.UserDataDir + Failed []Result +} + +type Plan struct { + Dirs []browser.UserDataDir // the discovered dirs, in output order + Files []snapshot.File // union of files to capture, deduplicated by (user data dir, path) + Extractions []Extraction // what will run, in output order (RFC-008) + Skipped []Result // requested but can't run: unsupported, absent, or Discovery.Failed +} + +func Discover(req Request) Discovery +func NewPlan(d Discovery, req Request) Plan +``` + +`Plan` is a plain value: printable, testable, and all `list` prints. `restore` builds its `Discovery` from the snapshot directory it opens instead of from the machine ([RFC-007](007-snapshot-and-acquisition.md)). + +## Outcome & Summary — `internal/app` + +```go +type Outcome int + +const ( + OutcomeOK Outcome = iota + 1 + OutcomePartial + OutcomeAbsent + OutcomeUnsupported + OutcomeError +) + +type Result struct { + Extraction + Outcome Outcome + Count int // records emitted + Failed int // Collector.Fail calls + Err error // set when Outcome == OutcomeError +} + +// Summary is what a run reports: every result, in output order. +type Summary struct { + Results []Result +} + +// Execute runs Capture, Extract, and Export one user data dir at a time (RFC-001). Its error means the run could +// not finish — an output write failure; every other failure is a Result. +func Execute(ctx context.Context, p Plan, req Request) (Summary, error) +``` + +The outcome follows from the counts: `OutcomeOK` when nothing failed — zero records included, since an empty source is not absent; `OutcomePartial` when records were emitted and some failed; `OutcomeError` when the extractor returned an error, a source failed to copy, or failures were reported with no record emitted. `Summary` starts with `Plan.Skipped`, so the report covers what never ran as well as what did. + +The exit status is not derived from `Summary`: it is `0` whenever the run completes and `1` when it cannot start or finish ([RFC-001](001-architecture-and-pipeline.md)). `Summary` feeds the report only. + +The stage functions are `Validate`, `Discover`, `NewPlan`, `Execute`, and `Report`; the values they produce are `Request`, `Discovery`, `Plan`, and `Summary`. No function shares a name with a type, which Go would reject. + +## Categories — `internal/category` + +What kind of browser data something is. Every stage speaks it: the CLI parses `-c` into it, a base package keys its `Extractors` by it, the planner crosses it with profiles, and the exporter names its files after it. + +```go +// Category is one kind of browser data. The zero Category means "none". +type Category int + +const ( + Password Category = iota + 1 + Cookie + Bookmark + History + Download + CreditCard + Extension + LocalStorage + SessionStorage +) + +// String returns "password", "cookie", "bookmark", "history", "download", "creditcard", +// "extension", "localstorage", "sessionstorage" — also the -c values and the output file names. +func (c Category) String() string + +func All() []Category // every category, in the order above +func Parse(s string) (Category, error) // the inverse of String, for -c +``` + +The package is tiny on purpose, like `timeconv`: it exists so that `category.Cookie` and `record.Cookie` can each mean exactly what they say ([RFC-004](004-naming-decisions.md)). There is no `Category.Sensitive()`: with `-c all` as the frozen default, nothing would consume it. + +## Record types — `internal/record` + +A record is one row of output — one saved login, one cookie, one history entry — and it has the same type whichever browser produced it. + +```go +// Login is one saved password: a URL, a user name, and a password together, as Chromium's "Login Data" +// and Firefox's logins.json keep them. +type Login struct { + Browser string `json:"browser" csv:"browser"` + Profile string `json:"profile" csv:"profile"` + URL string `json:"url" csv:"url"` + Username string `json:"username" csv:"username"` + Password string `json:"password" csv:"password"` + CreatedAt time.Time `json:"created_at" csv:"created_at"` + Store Store `json:"store" csv:"store"` +} + +// Store names the Chromium password database a Login came from. +type Store string + +const ( + StoreLocal Store = "local" // Login Data + StoreAccount Store = "account" // Login Data For Account +) + +// Record is a record of any category: one row of output. It is sealed: only this package's record types implement it. +type Record interface { + Category() category.Category + stamp(browser, profile string) +} + +// Stamp sets the two source fields every record starts with. The pipeline's Collector calls it on each record it is +// handed; it is exported because the sealing method stamp is not, and an unexported method can only be called from +// its own package. +func Stamp(r Record, browser, profile string) +``` + +| Category | Record type | Today's type | +| ------------------------- | ----------------------- | ----------------------- | +| `category.Password` | `record.Login` | `types.LoginEntry` | +| `category.Cookie` | `record.Cookie` | `types.CookieEntry` | +| `category.Bookmark` | `record.Bookmark` | `types.BookmarkEntry` | +| `category.History` | `record.History` | `types.HistoryEntry` | +| `category.Download` | `record.Download` | `types.DownloadEntry` | +| `category.CreditCard` | `record.CreditCard` | `types.CreditCardEntry` | +| `category.Extension` | `record.Extension` | `types.ExtensionEntry` | +| `category.LocalStorage` | `record.LocalStorage` | `types.StorageEntry` | +| `category.SessionStorage` | `record.SessionStorage` | `types.StorageEntry` | + +Every record type starts with two flat source fields, `Browser string` (the display name) and `Profile string` (`Profile.Name`), followed by today's fields with today's names, tags, and order. `LocalStorage` and `SessionStorage` declare the same fields separately, so each is its own type with its own category. Records are used by pointer — `out.Add(&record.Cookie{…})` — because `stamp` sets the fields in place. There is no `Origin`/`Owner` umbrella type ([RFC-004](004-naming-decisions.md)). + +Only the type names change. Field names are wire names — each field's snake_case form, enforced by lint — and because the output is frozen, so are they ([RFC-008](008-output-and-export.md)). `Store` becomes a named string type with today's two values, which changes nothing on the wire. + +## Master key — `internal/masterkey` + +```go +// Version is a Chromium ciphertext's version prefix. +type Version string + +const ( + V10 Version = "v10" + V11 Version = "v11" + V20 Version = "v20" +) + +// Set holds one Chromium user data dir's key per version. Its JSON form is today's keys.json +// "keys" object: {"v10": …, "v11": …, "v20": …}. +type Set map[Version][]byte + +// Retriever obtains one version's key from one OS secret store. Implementations are +// build-tagged and return ErrNotApplicable when they don't apply to this user data dir. +type Retriever interface { + Version() Version + Retrieve(ctx context.Context, loc Locator) ([]byte, error) +} + +// RetrieveAll runs this OS's retrievers in order. Per version the first key wins and later retrievers for that +// version are not tried; a version's error is reported only when all its retrievers fail. Versions are +// independent, so a v20 failure never discards a v10 key. +func RetrieveAll(ctx context.Context, loc Locator) (Set, error) +``` + +`Set` / `RetrieveAll` are **DECIDED** ([RFC-004](004-naming-decisions.md)). Because `Version` is a string type, `encoding/json` writes a `Set` with today's `"v10"` keys, sorted, and no marshaling code. Key scopes, retriever order, and laziness are in [RFC-006](006-key-retrieval-and-crypto.md). + +## Login keychain — `internal/keychain` + +```go +// PasswordFunc yields the macOS login password. app builds it from --keychain-pw, --keychain-pw-stdin, or the prompt +// (RFC-009); outside this package it is the only place the password exists. +type PasswordFunc func(ctx context.Context) (string, error) + +// Keychain is the user's login keychain. It opens on first use, at most once per run. +type Keychain struct{ /* unexported */ } + +// ErrLocked reports that no usable password was supplied, so the keychain yields metadata only. +var ErrLocked = errors.New("login keychain is locked") + +func New(path string, password PasswordFunc) *Keychain // no I/O: building one never prompts + +func (k *Keychain) GenericPassword(ctx context.Context, account string) ([]byte, error) // ErrLocked when locked +func (k *Keychain) InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) // secrets empty when locked +func (k *Keychain) Err() error // why it is locked; nil if open or never used +``` + +The login keychain belongs to the user, not to a profile or a user data dir, so one handle serves the whole run. On macOS `app` builds it and hands it to its two consumers: the Chromium `v10` retriever, through `masterkey.Locator`, and the Safari password extractor, which `safari.Extractors` captures for the default profile. Each consumer declares the one method it reads (`masterkey.LoginKeychain`, `safari.LoginKeychain`), so its tests need no real keychain. Opening the keychain is the password check: a missing or wrong password leaves it locked — metadata only, as today — and `Err` gives the reason, which the reporter prints once. The package builds only on macOS ([RFC-002](002-package-layout.md)); elsewhere, and in `restore`, there is no handle. Retrieval order and laziness are in [RFC-006](006-key-retrieval-and-crypto.md). + +## Snapshot — `internal/snapshot` + +```go +// File is one file or directory a plan wants captured. +type File struct { + DirID string // the user data dir's ID ("chrome", "arc-2"); also the snapshot it lands in + From string // absolute path of the user data dir it is copied from + Rel string // slash-separated path relative to From, and to the snapshot + IsDir bool +} + +// Dir is a snapshot directory: one Snapshot per user data dir. +type Dir struct{ /* unexported */ } + +func Temp() (*Dir, error) // a new temporary snapshot directory, mode 0700 +func Open(path string) (*Dir, error) // an existing one, used in place (restore --data-dir) +func Unzip(src string) (*Dir, error) // restore transport into a temporary snapshot directory; rejects entries that escape it + +func (d *Dir) Capture(ctx context.Context, files []File) error // copies what it can; per-file failures surface through Snapshot.Path +func (d *Dir) Snapshot(dirID string) Snapshot +func (d *Dir) Zip(dst string) error // archive: temp file beside dst, renamed into place on success +func (d *Dir) Close() error // removes a temporary snapshot directory; leaves an opened one in place + +// Snapshot is one user data dir's snapshot: the read-only view of the files captured from it. +type Snapshot struct{ /* unexported */ } + +// Path returns rel's absolute path inside the snapshot: fs.ErrNotExist when the file was never captured or had +// vanished before Capture reached it, or the copy's error when capturing it failed. +func (s Snapshot) Path(rel string) (string, error) +``` + +`Capture` returns an error only when it cannot go on — a cancelled context, an unwritable snapshot directory. A single file's failure is kept and handed back by `Snapshot.Path`, so it ends that file's extractions as `error` without stopping the rest. `snapshot` cannot import `browser` (`browser.ProfileSnapshot` holds a `snapshot.Snapshot`), so a `File` names its user data dir with a plain string, `DirID`. `Snapshot` hands out real paths because `modernc.org/sqlite` and `goleveldb` open files by path, and SQLite needs its `-wal` file beside the database. The snapshot is therefore always a directory; zip is only a transport format ([RFC-007](007-snapshot-and-acquisition.md)). + +## Export — `internal/export` + +```go +// Format is the -f value. Its zero value is JSON, the default. +type Format int + +const ( + JSON Format = iota + CSV + CookieEditor +) + +func ParseFormat(s string) (Format, error) // "json", "csv", "cookie-editor" + +// Writer appends each extraction's records to today's per-category files, in plan order. +type Writer struct{ /* unexported */ } + +func NewWriter(dir string, f Format, zip bool) (*Writer, error) +func (w *Writer) Write(c category.Category, records []record.Record) error // one extraction's records; the writer sorts them (RFC-008) +func (w *Writer) Close() error // finishes every file; with --zip, packs them +``` diff --git a/rfcs/004-naming-decisions.md b/rfcs/004-naming-decisions.md new file mode 100644 index 0000000..a92331d --- /dev/null +++ b/rfcs/004-naming-decisions.md @@ -0,0 +1,252 @@ +# RFC-004: Naming Decisions + +This is the one place the naming discussion lives. Each item keeps its rationale and the alternatives rejected, so the decisions are auditable rather than bare assertions. + +Go naming principles applied throughout: + +- **The package name is part of the identifier.** `category.Cookie` already says "the cookie category," so a `Category` prefix or a `record.Record`-style stutter is redundant. Names are judged at the call site, not in isolation. +- **A qualified name reads as what it is.** `category.Cookie` is a category and `record.Cookie` is a cookie record; neither needs a suffix to tell it from the other, because each lives in the package that means it. +- **A name says what a thing is, not how it is built or used, or what it resembles.** `ProfileSnapshot`, not `Input`; `Snapshot`, not `Tree`. +- **One concept, one name.** A user data dir's location is a `Path`, its identity a `DirID`, a ciphertext's prefix a `Version` — in code and in prose alike. +- **Values are nouns, stages are verbs.** A Go package cannot hold a type and a function of the same name, so the pipeline's values (`Plan`, `Summary`) and the stages that produce them (`NewPlan`, `Execute`) never share a word. + +Internal Go names are free to change; anything the user can see — commands, flags, file names, field names, `keys.json` keys — is frozen by the compatibility contract ([RFC-000](000-goals-and-constraints.md)), whatever the Go name behind it. + +## Settled (DECIDED) + +| Name | Decision | +| -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `internal/` for all non-`cmd` code | [RFC-002](002-package-layout.md). | +| `browser.Extractor` / `browser.Extractors` | The thing that declares sources and parses them. | +| `masterkey.Set` / `masterkey.RetrieveAll` | The key collection and the function that fills it. | +| Wire names = snake_case of Go field names | No second vocabulary; lint-enforced; frozen with the output. [RFC-008](008-output-and-export.md). | +| `browser` stays `browser` (not `engine`) | "Engine" means a web rendering engine (Blink/Gecko/WebKit) and misleads. | +| `browser.Supported()` / `browser.Lookup` | This OS's browsers / any row of the whole table. No `catalog` package. | +| `category.Category` with bare values; records `record.Login`, `record.Cookie`…; sum type `record.Record` | Categories and records in separate packages, so neither needs a suffix; no `model` package; the sum type takes its package's name, as `category.Category` does. | +| Per-record source: flat `Browser` + `Profile` | No `Origin`/`Owner` type; the fields hold today's output values. | +| `browser.ProfileSnapshot` | What an extractor is handed: its profile's view of the snapshot and the user data dir's keys (`Path`, `MasterKeys`); no `Secrets` handle, not `Input`. | +| `keychain.Keychain` | The run's macOS login keychain: one handle, opened on first use; consumers get the handle, never the password. | +| `browser.Collector` (`Add`, `Fail`) | What an extractor hands its records and record-level problems to; not `Sink`, not `Emit`. | +| `masterkey.Locator` / `chromium.KeyLocator` | Where one user data dir's keys are found, and the function that builds it; not `RetrieveInput`. | +| `Base` enum; product identity in `Def.ID` | No `Variant` enum; channel is folded into rows, not modelled. | +| `browser.UserDataDir` with a `DirID` | Not `Installation`; the ID has its own type. | +| `app` stages and values | `Validate`, `Discover`, `NewPlan`, `Execute`, `Report`; `Request`, `Discovery`, `Plan`, `Extraction`, `Summary`. | +| `snapshot.Dir` / `snapshot.Snapshot` | A snapshot directory and one user data dir's snapshot inside it, a snapshot being one user data dir's copy as in Chromium; not `FS`, `Tree`, or `Copy`. | +| `winapi`, `abe`; `log` and `crypto` kept | Windows-only packages; not `platform/windows`. | +| CLI names unchanged | `-c/--category` selects `category.Category` values; `-p/--profile-path` and `dumpkeys` stay. [RFC-009](009-cli-surface.md). | + +## Item-by-item detail + +### 1. The supported-browser table — `browser.Supported()` and `browser.Lookup` + +**Decision.** The table lives in `browser`, where it belongs; there is no `catalog` package. + +```go +browser.Supported() []browser.Def // the browsers HBD supports on the running OS, in table order +browser.Lookup(id string) (Def, bool) // any row of the whole table, whatever the OS +``` + +`Supported()` is exactly what its callers need: Discover walks it, `-b` is validated against it, and the help text lists it. It reads as "the browsers that are supported," and on macOS that list must not contain `qq` or `sogou`, which have no macOS row. `restore` needs the other view — a vault taken on Windows can name a Windows-only fork — so it resolves IDs with `Lookup`, which searches the whole table. No caller needs the whole table as a list; tests that do read the package's unexported table. + +**Alternatives rejected.** + +| Option | Why not | +| --------------------------------------- | ------------------------------------------------------------------------------------------- | +| `catalog.All()` | "all of the catalog" says nothing about _what_; the `catalog` noun doesn't pull its weight. | +| `registry.All()` | "registry" is implementation jargon; same empty `All()`. | +| `catalog.Browsers()` | keeps the `catalog` noun. | +| `browser.Known()` | an honest name for the whole table, but no caller wants the whole table as a list. | +| `Supported()` returning every OS's rows | the name would promise "supported here" and deliver "known anywhere." | + +### 2. Per-record source — flat `Browser` + `Profile`, no umbrella type + +**Decision.** Each record carries two flat fields — `Browser string` and `Profile string` — not a wrapper type. `Browser` holds `Def.Name`, the display name (`Chrome`, `Microsoft Edge`), and `Profile` holds `Profile.Name` (`Default`, or a Safari profile's title) — exactly the values today's `browser` and `profile` columns carry. Putting `Def.ID` (`chrome`) in `Browser` would change every row, which the compatibility contract rules out. + +**Why no umbrella type.** `Owner` is wrong (it implies possession/ACLs). `Origin` is worse in this domain: "origin" is already the Web-platform term (`scheme://host:port`), so `cookie.Origin` reads as "the site this cookie belongs to," not "where I pulled it from" — the same collision that got `engine` rejected. `Provenance` is the DFIR term but reads heavy. The browser domain has no clean single noun for "(browser, profile) a datum came from", so the record stamps a `browser` and a `profile` column, as today's output already does. + +**`Profile` holds the name, never a path.** This keeps local absolute paths out of exported data and keeps archives portable across hosts. It does not collide with the `browser.Profile` type or with `Profile.Dir` (the path) — a field named `Profile` of type `string` lives in a different namespace from the type. + +**Stamping.** The fields are exported so `encoding/json` serializes them, but extractors don't set them: the pipeline's `Collector` calls `record.Stamp` on every record it is handed. `Stamp` is exported because `Record`'s sealing method `stamp` is not, and Go only lets the declaring package call an unexported method. + +On the wire: `browser` and `profile` keys in JSON; leading `browser` / `profile` columns in CSV. + +**Alternatives rejected.** + +| Option | Why not | +| ----------------- | ---------------------------------------------------------------- | +| `Origin` type | collides with Web-platform "origin" in a browser-data tool. | +| `Provenance` type | accurate (DFIR) but heavy, and still an invented umbrella. | +| `Source` type | `browser.Source` is the extractor's file set; two "Source"s mix. | + +### 3. The extractor's input — `browser.ProfileSnapshot` + +**Decision.** An extractor is handed a `browser.ProfileSnapshot`: its profile's view of the user data dir's snapshot, plus the dir's Chromium keys. It is a concrete type with two methods, built by `app` through `NewProfileSnapshot`: + +```go +func (ps ProfileSnapshot) Path(src Source) (string, error) // where src was captured in the snapshot +func (ps ProfileSnapshot) MasterKeys(ctx context.Context) masterkey.Set // this user data dir's Chromium keys; the first call retrieves +``` + +**Why `ProfileSnapshot`.** It names what the extractor holds — one profile's share of the snapshot — where `Input` named only a role: every function has inputs. `ps.Path(loginData)` and `ps.MasterKeys(ctx)` read as what they return. + +**Why no `Secrets` handle.** A `Secrets` interface wrapping the keys and the macOS login password was considered. Master keys and the login password have nothing in common but being secret; the domain has no clean noun for both, and inventing one is the fault item 2 rejects for `Origin` and `Owner`. Without the password (item 8), `Secrets` would be a one-method interface that `app` implements and every extractor reaches through; the method sits better on the value the extractor already holds. The laziness stays where it was — a per-user-data-dir call-once in `app`, passed in as a function — so extractors depend on having keys, not on how they are fetched. + +**Why no error.** `MasterKeys` returns only the `Set`. A retrieval failure concerns the whole user data dir, so `app`'s call-once reports it once, as that dir's `error` result; the extractor finds the version's key missing and reports the affected records through `Collector.Fail`, as it would any secret it cannot recover. + +**Alternatives rejected.** + +| Option | Why not | +| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `browser.Input` | names a role, not a thing. | +| `browser.Secrets{MasterKeys, KeychainPassword}` | an invented umbrella over two unrelated secrets (item 2's rule); the password does not belong on the extractor's input at all (item 8). | +| `masterkey.Lazy` | names a strategy, not what the extractor holds. | +| `masterkey.Keys{Set()}` | `in.Keys.Set()` reads as a setter in Go (`flag.Value.Set`, `http.Header.Set`), and `masterkey.Keys` stutters. | + +### 4. Browser classification — `Base`, with product identity in `ID` + +Anchored in Chromium's own vocabulary (`install_modes.h` calls the product axis _brand_; the older `BrowserDistribution` called it _distribution_). + +**Decision.** + +- **`Base`** is the single classification enum: `Chromium`, `Firefox`, `Safari`. It is the "what is this built on" axis — "Chromium-based" — and it decides the storage/decryption model and which base package handles it. What these browsers share is the **Chromium platform/codebase**, not the rendering engine (Blink), which is exactly why `engine` would be both a collision and imprecise. +- **Product/brand identity lives in `Def.ID`** (a string, e.g. `"chrome"`, `"edge"`). There is **no `Variant` enum.** Modelling the product axis as an enum would force a code change for every new fork, which fights the "add a fork = add a data row" goal ([RFC-005](005-browser-definitions.md)); a string `ID` keeps forks as pure data. The few forks with their own on-disk format (Yandex, the Opera family) get an override inside the Chromium package keyed by `Def.ID` — still no enum, and a plain fork stays a pure row. +- **Channel** (stable/beta/dev/canary) is a separate axis in Chromium (install modes), but HBD gives it no field, because nothing dispatches on it: a channel that keeps its own user data dir is simply its own row, whose `ID` names product and channel together (`chrome-beta`). + +**Alternatives rejected.** + +| Axis | Option | Why not | +| ------- | ------------------------ | --------------------------------------------------------------------------------- | +| base | `Family` | common informal word, but not domain-native; `Base` reads "Chromium-based". | +| base | `Engine` | rejected project-wide; also imprecise (renderer ≠ storage model). | +| base | `Platform` | means OS, not codebase — it is the per-OS half of a `Def` (item 6), not the base. | +| product | `Variant` / `Brand` enum | a per-fork enum fights "fork = data row"; identity belongs in `ID`. | +| channel | a `Channel` field | nothing reads it; the row and its `ID` already say it. | + +### 5. Data categories and records — `category` and `record` + +**Decision.** Two small packages, each with bare names: + +```go +category.Password, category.Cookie, category.Bookmark, category.History, +category.Download, category.CreditCard, category.Extension, +category.LocalStorage, category.SessionStorage + +record.Login, record.Cookie, record.Bookmark, record.History, +record.Download, record.CreditCard, record.Extension, +record.LocalStorage, record.SessionStorage +``` + +A category says what kind of data is meant; a record is one row of that data. The two share their nouns — a cookie category, a cookie record — so in one package one of them would need a suffix, and a reader of `record.Cookie` would take a category for a record. In two packages each qualified name reads as what it is: `extractors[category.Cookie]`, `out.Add(&record.Cookie{…})`, and `-c cookie` → `category.Parse` → `category.Cookie` → `cookie.json`. The `Category.String()` values (`password`, `creditcard`, `localstorage`, …) are the `-c` values and the output file names, so they are frozen. + +**Why `Category`, not `Kind`.** The CLI already calls it a category — `-c/--category`, "data categories" in the help text — and so does today's code (`types.Category`), so one concept keeps one name from the flag to the type. "Kind" already means other things here: the frozen `kind` field of a `keys.json` vault (`chromium-yandex`), today's `types.BrowserKind`, and `masterkey.ABEKind`. The constants stay bare: the `CategoryCookie` prefix is what fought the package name, not the type's name. The type reads `category.Category`, the accepted Go form for a package's main type (`time.Time`); a variable holding one is `c`, since `category` would shadow the package. Numbering starts at 1, so the zero `Category` means "none": a result about a whole user data dir has no category, and an unset field never reads as `Password`. + +**Why `Login` for the password record.** The category is `password`, a frozen `-c` value, but the record holds a URL, a user name, and a password together — Chromium's "Login Data", Firefox's `logins.json`, today's `LoginEntry` — and a `record.Password` with a `Password` field would read `p.Password`. Every other record shares its category's name. + +**Why `Record` for the sum type.** Every record type implements `record.Record`, so `record.Cookie` reads as a kind of `record.Record`. The type takes its package's name for the reason `category.Category` does — the accepted Go form for a package's main type (`time.Time`); `Item` said nothing about what it holds. + +**Alternatives rejected.** + +| Option | Why not | +| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| `record.Kind` beside `record.CookieItem`… in one package | `record.Cookie` would be a category, not a record, and every record would carry an `Item` suffix. | +| `Category` + `CategoryCookie`… | the prefix repeats the package's meaning at every call site. | +| `Kind` | a Go-insider word, and "kind" already names a vault's browser variant and the ABE dispatch. | +| `record.Password` | `p.Password` stutters; the row is a login. | +| package `model` | says nothing about what it models. | +| sum type `record.Item` | says nothing about what it holds; the `time.Time` form that gives `category.Category` gives `record.Record`. | + +### 6. The data-directory type — `browser.UserDataDir`, not `Installation` + +**Decision.** The type for one browser data directory found on a machine is `browser.UserDataDir`, identified by a `browser.DirID`. + +**Why not `Installation`.** In both Chromium and Firefox, an "installation" is the _program_ — the executable and its files. The thing this type holds is the _data_ directory: Chromium's `User Data` (the `--user-data-dir` the browser documents), Firefox's `Profiles` directory, Safari's data under `~/Library`. Three reasons `Installation` is wrong for it: + +1. It collides with the program sense already in the table: `Platform.Exe` and `ExeFallbacks` point at the _installation_. One document should not use "install" for two different things. +2. A machine can have several data directories for one installed program (Arc's two MSIX packages), so "one installation" misdescribes the count. +3. In `restore` the directory was copied from another host and was never installed here at all. + +`UserDataDir` is Chromium's own term, and it already appears in today's code (`BrowserConfig.UserDataDir`) and in the frozen `keys.json` field `user_data_dir` — so the type name aligns with a word the codebase and the output already use. Firefox and Safari have no such word; for them it means the directory their sources resolve under ([RFC-003](003-core-types.md)). + +**Why `DirID` is its own type.** A user data dir's ID (`arc-2`) and its browser's `Def.ID` (`arc`) are equal for the first directory of every browser, so code that passes one where the other belongs passes every test on a machine with one Arc. As distinct types, the mix-up does not compile. + +**Supporting names.** + +| Name | What it names | Why this name | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `UserDataDir.ID` (`DirID`) | `chrome`, `arc`, `arc-2` — one per data directory found | Distinguishes two user data dirs of one `Def`; also the snapshot and archive directory name. | +| `UserDataDir.Def` | the directory's `Def` | A field named for its type, the Go norm; `Browser` would clash with the record's `Browser string`. | +| `UserDataDir.Path` | its absolute path | The one word for a user data dir's location; `Root` was rejected as a second word for it. | +| `Platform.UserDataDirs` | where one browser's user data dirs live on one OS | Each match becomes a `UserDataDir`; `Roots` would be another word for the same thing. | +| `Platform` fields | `UserDataDirs`, `KeychainLabel`, `Exe`, `ExeFallbacks`, `ABE` | The per-OS half of a `Def`; absorbs `winutil.Entry`. `Platform` means OS here (where `Base` means codebase), so the two never collide. | +| `browser.Source` / `browser.Collector` | the files an extractor reads / what it hands its records to | Says what it does with records, where `Sink` is dataflow jargon. `Add` is Go's verb for putting something into a container (`Emit` is event-framework vocabulary); `Collector.Fail` is what makes `partial` countable. | +| `Source.Shared` | a source of the whole user data dir (`Local State`) | Explicit data; the alternative made correctness depend on the order of builder calls ([RFC-005](005-browser-definitions.md)). | +| `browser.DiscoverOptions` | the home dir and `-p` handed to Discover | Today's name in `browser/browser.go`; kept. | +| `masterkey.Version` | `v10`, `v11`, `v20` | Chromium's own word (`kEncryptionVersionPrefix`); a string type, so a `Set` marshals to today's `"v10"` keys with no extra code. "Tier" is not used. | +| `masterkey.ABEKind` | `ABENone`, `ABEChromeBase`, `ABEEdge`, `ABEAvast` | Today's `winutil.ABEKind`, moved to the package that consumes it. | +| `masterkey.Locator` | where one user data dir's keys are found: the `Local State` copy, the keychain label, the Windows `Exe` and `ABE` kind, the run's login keychain | Names what it holds; `RetrieveInput` named only a role, the fault item 3 rejects in `Input`, and `Hints` sounds optional. `chromium.KeyLocator` builds one. | + +### 7. Pipeline and package names — `app`, `snapshot`, `winapi` + +**`app`: nouns for values, verbs for stages.** `Validate` produces a `Request`, `Discover` a `Discovery`, `NewPlan` a `Plan`, `Execute` a `Summary`, and `Report` writes the summary out. `Run` is not used as a type name: in Go it reads as a verb (`cmd.Run`, `t.Run`). + +**`Extraction`, not `Job`.** A plan's unit of work is one extraction: one category of data from one profile of one user data dir. `Job` beside `Result` is the vocabulary of Go's worker-pool idiom — `jobs` and `results` channels — so a reader looks for goroutines and a queue that do not exist. `Extraction` names what HBD does, extract browser data, and pairs with `Extract` and `Extractor` without suggesting concurrency. It sits one package away from `browser.Extractors`, a near-homonym, which the package names keep apart. + +**`snapshot.Dir` and `snapshot.Snapshot`, not `snapshot.FS`, `snapshot.Tree`, or `snapshot.Copy`.** A Go reader takes `FS` for `io/fs.FS`; this type is not one, and it returns operating-system paths because SQLite and LevelDB open files by path. A `Snapshot` is one user data dir's snapshot, in Chromium's own sense of the word: its `downgrade::SnapshotManager` takes a snapshot by copying selected files of one user data dir. A `Dir` is the snapshot directory that holds one `Snapshot` per user data dir, and `Dir.Snapshot(dirID)` returns one — a method named for what it returns, as `http.Request.Cookie(name)` is. `ProfileSnapshot` is then one profile's share of a `Snapshot`, so the vocabulary closes. Both are concrete types, and the snapshot directory's lifecycle — created with mode `0700`, removed by `Close` — lives in `Dir`'s methods rather than in free functions over a named string. `Zip` and `Unzip` are the transport pair. + +**`winapi` and `abe`, not `platform/windows`.** A package named `windows` would collide with `golang.org/x/sys/windows`, which it imports, so every file would need an alias. `winapi` is today's name; the ABE bridge becomes its own package, `abe`. + +**`log` and `crypto` keep their names.** Both share a name with a standard-library package, but both are internal and no file needs both, and both are today's names. + +**Alternatives rejected.** + +| Option | Why not | +| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type Plan` + `func Plan`, `type Run` | a type and a function can't share a name; `Run` reads as a verb. | +| `Job`, `Task` | Go's worker-pool vocabulary (`jobs` / `results` channels); readers look for a queue. | +| `Target` | reads as an attack target in a security tool. | +| `Unit`, `Item`, `Entry` | `Unit` and `Item` say nothing; `…Entry` names today's record types. | +| `snapshot.FS` | reads as `io/fs.FS`. | +| `snapshot.Tree` | a metaphor for its shape, not a name for what it holds. | +| `snapshot.Files` | collides with `snapshot.File`, a capture request, and `Plan.Files`. | +| `snapshot.Copy` | reads as a verb in Go (`io.Copy`, the `copy` builtin), next to `Capture`, the method that does copy. | +| `Dir.CopyOf`, `Dir.Get`, `Dir.Lookup`, `Dir.Sub` | `CopyOf` reads as making a copy (Java's `Arrays.copyOf`); `Get` and `Lookup` say less than a method named for what it returns; `Sub` brings back the subtree metaphor (`fs.Sub`). | +| `type Dir string` with free functions | the snapshot directory's lifecycle belongs on the type. | +| `platform/windows` | collides with `golang.org/x/sys/windows`. | +| `logx` | renames today's package for no reader's benefit, and `crypto` would then need the same treatment. | + +### 8. The macOS login keychain — `keychain.Keychain` + +**Decision.** The login keychain is a resource with one owner, the macOS-only package `internal/keychain`. `keychain.New(path, password)` returns a `*keychain.Keychain` that opens on first use, at most once per run. The macOS Chromium `v10` retriever and the Safari password extractor receive the handle; the password itself goes only from `keychain.PasswordFunc` into the keychain. The type reads `keychain.Keychain`, the accepted Go form for a package's main type (`time.Time`), as `category.Category` does. + +**Why a handle, not a password.** Today the password travels as a string — through `DiscoverOptions`, a setter interface, the retriever constructor, and four Safari function signatures — and every consumer reopens the keychain to use it. A password that was checked and then passed on as a string has to be trusted downstream; an opened keychain carries its own answer: open, or locked with a reason. The keychain belongs to the user, so its scope is the run; as a method on the per-profile extractor input it would put a run-scoped, macOS-only concept on a cross-platform, per-profile type. Each consumer declares the one method it uses — `masterkey.LoginKeychain`, `safari.LoginKeychain` — under the same name, since both name the same thing. + +**Alternatives rejected.** + +| Option | Why not | +| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `ProfileSnapshot.KeychainPassword(ctx)` | hands out the credential instead of the resource; every consumer reopens the keychain; a macOS-only method on every extractor's input. | +| a password function in the `masterkey.Locator` | a second path for the same secret, beside the extractor input. | +| `keychain.Login` | collides with `record.Login`, a saved login. | +| `masterkey.Keychain` | `masterkey` holds Chromium keys; Safari's saved logins are not keys. | + +## Summary table + +| Concept | Decision | Rejected | +| ----------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| Supported-browser table | `browser.Supported()` (this OS) + `browser.Lookup` (whole table) | `catalog.All()`, `registry.All()`, `browser.Known()` | +| Per-record source | flat `Browser` + `Profile`, set by `record.Stamp` | `Owner`, `Origin`, `Provenance`, `Source` types | +| Extractor input | `browser.ProfileSnapshot{Path, MasterKeys}` | `browser.Input`, `browser.Secrets`, `masterkey.Lazy`, `masterkey.Keys{Set}` | +| macOS login keychain | `keychain.Keychain`: one per run, opened on first use | `ProfileSnapshot.KeychainPassword`, a password function in the `Locator`, `keychain.Login`, `masterkey.Keychain` | +| Browser base | `Base` (Chromium / Firefox / Safari) | `Family`, `Engine`, `Platform` | +| Browser product | `Def.ID` (no enum); format overrides keyed by ID | `Variant` / `Brand` enum | +| Data categories | `category.Category` + bare `category.Cookie`…; zero is "none" | `record.Kind`, `CategoryCookie`…, `model` | +| Records | `record.Login`, `record.Cookie`…; sealed `record.Record` | `record.CookieItem`, `record.Password`, `record.Item` | +| Data directory | `browser.UserDataDir`, identified by a `DirID` | `Installation` | +| Extractor output | `browser.Collector` (`Add` + `Fail`) | `browser.Sink`, `Emit`, an `Emit` func, `Output`, `Recorder` | +| Key retrieval input | `masterkey.Locator`, built by `chromium.KeyLocator` | `masterkey.RetrieveInput`, `Hints` | +| Pipeline values | `Discovery`, `Plan`, `Summary` | `type Run` | +| Unit of work | `app.Extraction{DirID, Profile, Category}` | `Job`, `Task`, `Target`, `Unit` | +| Snapshot | `snapshot.Dir` + `snapshot.Snapshot`, returned by `Dir.Snapshot(dirID)` | `snapshot.FS`, `snapshot.Tree`, `snapshot.Copy`, `snapshot.Files`, `Dir.CopyOf`, `type Dir string` | +| Windows packages | `winapi`, `abe` | `platform/windows` | + +The only cross-row couplings: the `category` package and the bare record names are one decision, and the flat `Browser`/`Profile` source replaces every mention of `Origin`. diff --git a/rfcs/005-browser-definitions.md b/rfcs/005-browser-definitions.md new file mode 100644 index 0000000..6eccce6 --- /dev/null +++ b/rfcs/005-browser-definitions.md @@ -0,0 +1,146 @@ +# RFC-005: Browser Definitions + +## The table + +HBD knows a fixed set of browsers. Each is a `browser.Def`: a static description of how the browser is classified and how it appears on each OS. The table is data, not code — adding a plain fork is adding a row. + +```go +type Def struct { + ID string // CLI -b value and keys.json vault key; also the first user data dir's DirID: "chrome" + Name string // display name, stamped on every record: "Chrome" + Base Base // Chromium | Firefox | Safari — the only classification enum (RFC-004) + + Darwin Platform // no UserDataDirs ⇒ not supported on that OS + Linux Platform + Windows Platform +} + +type Base int + +const ( + Chromium Base = iota + 1 + Firefox + Safari +) + +// Platform is how one browser appears on one OS. +type Platform struct { + UserDataDirs []string // relative to the home dir; globs allowed; every match is its own UserDataDir + KeychainLabel string // macOS Keychain account / Linux Secret Service label; "" = none + Exe string // Windows: the browser program's executable, used by ABE ("chrome.exe") + ExeFallbacks []string // Windows: program paths tried when the registry has no App Paths entry + ABE masterkey.ABEKind // Windows: App-Bound Encryption dispatch; ABENone = DPAPI only +} +``` + +A row, for scale: + +```go +{ + ID: "chrome", Name: "Chrome", Base: Chromium, + Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Google/Chrome"}, KeychainLabel: "Chrome"}, + Linux: Platform{UserDataDirs: []string{".config/google-chrome"}, KeychainLabel: "Chrome Safe Storage"}, + Windows: Platform{ + UserDataDirs: []string{"AppData/Local/Google/Chrome/User Data"}, + Exe: "chrome.exe", + ExeFallbacks: []string{`%ProgramFiles%\Google\Chrome\Application\chrome.exe`, …}, + ABE: masterkey.ABEChromeBase, + }, +}, +``` + +The per-OS fields are what today's code spreads across three places: the `KeychainLabel` of each `types.BrowserConfig`, the `WindowsABE` flag, and the separate `winutil.Table` entry joined to it by key. Each fork's label differs per OS (Edge uses `Microsoft Edge` on macOS but `Chromium Safe Storage` on Linux), which is why the label lives in `Platform`, not on `Def`. `UserDataDirs` names data directories; `Exe` and `ExeFallbacks` name the program installation — two different things, kept apart in name as well ([RFC-004](004-naming-decisions.md)). + +One table serves every OS. `Def.Platform()` returns the running OS's entry (a build-tagged one-liner). `Supported()` returns the rows whose entry has `UserDataDirs` — the per-OS list today's help text shows, and exactly what `-b` accepts. `Lookup` searches the whole table, so `restore` resolves a vault's `Def` whatever the host OS and a Windows-only fork restores on macOS ([RFC-007](007-snapshot-and-acquisition.md)). + +Two axes, kept apart ([RFC-004](004-naming-decisions.md)). `Base` is the only enum and answers "what is this built on" — it selects the base package and the key path. Product/brand identity is just `ID` (a string), so a new fork is a new row, not a new enum constant. Release channel (stable/beta/dev/canary) gets no field, because nothing dispatches on it: each installed channel that keeps its own user data dir is its own `Def`, with an `ID` that names product and channel together (`chrome-beta`). + +Accessors (names per [RFC-004](004-naming-decisions.md)): + +```go +browser.Supported() []Def // this OS's rows, in table order +browser.Lookup(id string) (Def, bool) // any row, whatever the OS +``` + +## How a browser produces data + +`Def` says _where_. `Base` says _how_. Each base package supplies two functions: + +```go +// one per base, in internal/browser/{chromium,firefox,safari} +func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) +func Extractors(dir browser.UserDataDir, p browser.Profile) browser.Extractors +``` + +`app` calls them through a `switch def.Base`. The dispatch cannot live in `browser`: the base packages import `browser` for these very types, so `browser` calling them would be an import cycle, and `gochecknoinits` rules out init-time registration. These are plain functions, not an interface named `Engine` — that word is rejected project-wide. + +The Chromium base supplies two more, for the files no single category owns (below): + +```go +// internal/browser/chromium only +func KeyLocator(dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Locator, error) +func ArchiveSources(dir browser.UserDataDir) []browser.Source +``` + +Safari's `Extractors` takes one more argument, the run's login keychain, which its password extractor captures. Only the default profile's map gets a password extractor, because the keychain belongs to the user, not to one profile ([RFC-006](006-key-retrieval-and-crypto.md)). `LoginKeychain` is the one-method interface Safari declares; `*keychain.Keychain` satisfies it. + +```go +// internal/browser/safari only +func Extractors(dir browser.UserDataDir, p browser.Profile, kc LoginKeychain) browser.Extractors +``` + +## Discovery + +Discovery answers one question — which user data dirs and profiles exist — and nothing else. Its rules: + +- **Explicit inputs.** Everything comes in through `DiscoverOptions`. `app` resolves the home directory once; if that fails the run stops with status `1`. Today `browser/consts.go` resolves it in a package-level variable with the error discarded, so a failure silently turns every path into a wrong absolute one, and tests cannot substitute a home directory. +- **Every match counts.** Every `UserDataDirs` entry is expanded, globs included, and **every** existing match becomes its own `UserDataDir` — today's `resolveGlobs` behavior, which is what keeps the user data dirs of both of a machine's Arc MSIX packages. The first one of a `Def` gets the `DirID` `Def.ID`, later ones `-2`, `-3`… in path order, so IDs are stable from run to run. +- **Errors are not absence.** A user data dir that does not exist yields nothing. Any other failure — permission denied, a malformed glob — is returned (joined across entries, next to whatever was found) and becomes an `error` result for that browser in the summary. Today both the Chromium and the Firefox profile scans return nothing on any read error, and `resolveGlobs` drops glob errors and keeps an unmatched pattern as a literal path, so "unreadable" looks exactly like "not installed". +- **Profiles by today's rules.** Chromium directories holding `Preferences` or `Preferences_02` (Tencent forks), with flat-layout and copied-tree fallbacks; Firefox directories holding known data files; Safari's default profile plus its named profiles (macOS 14+). The named profiles are listed only inside `SafariTabs.db`, so Safari's Discover captures that one file into a temporary snapshot with the snapshot copier and reads the copy; today it opens the live database. +- **No source checks.** Whether a category's file exists is Plan's question, answered as `absent`. Today `NewBrowser` checks every source while constructing the browser and silently drops a profile that has none; `list` keeps today's display rule (profiles with at least one source), but the decision moves out of discovery. +- **`-p` replaces `UserDataDirs` for one `Def`.** When `DiscoverOptions.ProfilePath` is set, discovery reads that path instead of the table's entries, and each base interprets it by the rules in [RFC-009](009-cli-surface.md). + +## Per-fork overrides — data stays data + +Most Chromium forks are pure rows. A few store data their own way, and today they get their own `types.BrowserKind` values with `if kind == …` checks across files: + +| Fork IDs | What differs | Override | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- | +| `yandex` | `Ya Passman Data` and `Ya Credit Cards`, with Yandex's own key wrapping and row format; no account-store passwords | password and credit-card sources and extractors | +| `opera`, `opera-gx`, `vought` | extensions under `extensions.opsettings` | extension extractor | + +In the rewrite these overrides live inside `internal/browser/chromium`, in one unexported table keyed by `Def.ID` — never by the `DirID`, which differs for a second user data dir — applied when `Extractors` builds a profile's map. No enum is involved and the browser table stays free of code. A unit test asserts that every override key resolves through `Lookup` to a Chromium `Def`, so a typo cannot silently drop an override. + +`keys.json` keeps writing today's `kind` values (`chromium`, `chromium-yandex`, `chromium-opera`), derived from the same table, so v1.1.0 can still read a new dump. When reading, `restore` resolves the `Def` from the vault's `browser` ID and falls back to `kind` only for an ID this build doesn't know. + +## Shared and per-profile files + +Most sources belong to one profile (cookies, history) and are declared relative to the profile directory. A few belong to the whole user data dir — `Local State` above all — and are marked `Shared`, relative to the user data dir itself ([RFC-003](003-core-types.md)). Plan resolves both into paths under the user data dir and captures the union once per user data dir, so `Local State` is copied once however many profiles and categories need it. The flag is explicit on purpose: rewriting every source path per profile while remembering to leave the shared ones alone would make correctness depend on the order of two builder calls. + +Two Chromium facts concern a whole user data dir rather than one category, and both stay in the Chromium base, so `app` never spells a Chromium file name: + +- **Key material.** The extractors that decrypt — passwords, cookies, credit cards — list `Local State` as a `Shared` source, so it is captured only when a decrypting category is requested. `KeyLocator` builds the dir's `masterkey.Locator` from the captured `Local State` and the `Platform` fields; on macOS `app` adds the run's login keychain, then wraps retrieval in the dir's call-once, which every `ProfileSnapshot` of the dir shares as its `MasterKeys` ([RFC-006](006-key-retrieval-and-crypto.md)). +- **Layout markers.** `archive` also captures `Local State` and each profile's `Preferences` (or `Preferences_02`) marker, so a reader without the manifest can still find every profile; `ArchiveSources` names them. + +## Adding a browser (the whole motion) + +For a new Chromium fork: + +1. **Add a row** to the table in `internal/browser`: `ID`, `Name`, `Base: Chromium`, and a `Platform` per OS (user data dirs, keychain label; on Windows `Exe`, `ExeFallbacks`, `ABE`). +2. **If `ABE` is not `ABENone`**, add the fork's row to the payload's `com_iid.c` — the CLSID/IIDs and vtable slot the injected payload needs. The technique and how to mine those identifiers are in [RFC-016](016-chrome-abe-integration.md). +3. **Only for a fork with its own on-disk format**, add an override in the Chromium package. +4. **Nothing else.** The fork inherits the entire Chromium base: discovery, every extractor, the key path, snapshot, export, reporting. + +For a genuinely new base (not Chromium/Firefox/Safari), you add a new `internal/browser/` package implementing `Discover` + `Extractors`, a new `Base` value, and a case in `app`'s switch. This is rare — the three bases cover the field. + +## Consistency, enforced by tests + +Folding `winutil.Table` into `Platform` removes the Go-side join, and with it the need for today's `TestWinUtilTableCoversABEBrowsers`: one struct cannot disagree with itself. What remains is the C side — the payload runs inside the browser process with no Go runtime, so its table stays in `com_iid.c`. A Go test inside `browser`, over the whole table, parses that file and fails when its set of executables and ABE kinds differs from the Windows entries whose `ABE` is not `ABENone` ([RFC-011](011-testing-and-quality.md)). A mismatch fails `go test`, not production. + +## Why a table beats per-browser types + +The current design has per-OS `platformBrowsers()` lists of `BrowserConfig`, a `WindowsABE` flag, a Windows table joined by key, and two Chromium kinds switched on across files. The table collapses that to rows + three base packages + a short override table. The payoff: + +- The set of supported browsers is **legible in one place** — good for the README, good for a talk slide, good for auditing coverage across all three OSes at once. +- A plain fork is a data change, reviewable at a glance. +- Base behavior is implemented three times total, not once per browser. diff --git a/rfcs/006-key-retrieval-and-crypto.md b/rfcs/006-key-retrieval-and-crypto.md new file mode 100644 index 0000000..fdd7750 --- /dev/null +++ b/rfcs/006-key-retrieval-and-crypto.md @@ -0,0 +1,79 @@ +# RFC-006: Key Retrieval & Crypto + +**Scope note.** This RFC fixes the _boundaries and contracts_ of the key-retrieval and decryption packages. It deliberately does not restate how any OS secret store is read or how any cipher is applied — those techniques are already documented in [RFC-014](014-chromium-encryption.md) (Chromium encryption), [RFC-015](015-key-retrieval-mechanisms.md) (key retrieval), [RFC-016](016-chrome-abe-integration.md) (Chrome ABE), [RFC-017](017-yandex-decryption.md) (Yandex), [RFC-019](019-firefox-encryption.md) (Firefox encryption), and [RFC-021](021-windows-locked-file-bypass.md) (Windows locked-file). Here each is simply a package with an interface. + +## Two packages, one seam + +- **`internal/masterkey`** owns everything that talks to an OS secret store: retrieving a Chromium user data dir's keys, one per version (DPAPI and ABE on Windows, Keychain on macOS, Secret Service on Linux), decrypting legacy per-value DPAPI blobs, and the portable `keys.json` dump. Platform code sits behind build tags; callers import one package. It knows nothing about records or browsers. +- **`internal/crypto`** holds pure primitives over bytes: AES-CBC and AES-GCM, 3DES, PBKDF2, and the ASN.1 PBE structures Firefox's NSS uses. It takes raw keys, nonces, and ciphertexts, makes no OS calls, and imports nothing from the project — which is what keeps it unit-testable with fixed vectors. It knows no blob format: Chromium's version prefix and nonce layout belong to the Chromium base, and Yandex's to its override. + +`masterkey` calls `crypto`; `crypto` never sees a `masterkey.Set`. A decrypt that took a `Set` would have to live in one of the two packages and call back into the other — an import cycle — so dispatch lives with the format that defines it (below). + +A third package sits beside them on macOS only: **`internal/keychain`** owns the user's login keychain — one handle per run, opened on first use, read by the Chromium `v10` retriever and the Safari password extractor. The login password, supplied by the CLI ([RFC-009](009-cli-surface.md)), reaches no other code. + +## Key scopes + +Different bases keep their secrets at different levels, so "once per user data dir" is not universal: + +| Base | Scope | Where the secret comes from | Lazy handle | +| -------- | ------------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------- | +| Chromium | user data dir | `Local State` from the snapshot, plus the OS secret store — on macOS, that includes the run's login keychain | `ProfileSnapshot.MasterKeys` | +| Firefox | profile | the profile's own `key4.db`, validated against its `logins.json` — no OS store, no prompt | derived inside the Firefox password extractor | +| Safari | run | the login keychain, opened once per run | `keychain.Keychain`, captured by the Safari password extractor | + +Two edge cases sit outside the table. Legacy Windows Chromium values without a `v10` prefix are raw DPAPI blobs, decrypted one by one through `masterkey.DecryptDPAPI` with the live user's DPAPI context — they never decrypt on another host. And on macOS the Chromium `v10` retriever and the Safari password extractor read the same login keychain, so the keychain is opened once per run and shared ([RFC-003](003-core-types.md); [RFC-009](009-cli-surface.md) defines how its password is supplied). + +## `masterkey` contract + +```go +type Version string // "v10", "v11", "v20" +type Set map[Version][]byte // JSON form = today's keys.json "keys" object + +type Retriever interface { + Version() Version + Retrieve(ctx context.Context, loc Locator) ([]byte, error) +} + +// LoginKeychain is what the macOS v10 retriever reads from the run's login keychain; *keychain.Keychain satisfies it. +type LoginKeychain interface { + GenericPassword(ctx context.Context, account string) ([]byte, error) // keychain.ErrLocked: no usable password +} + +var ErrNotApplicable = errors.New("retriever not applicable") + +func RetrieveAll(ctx context.Context, loc Locator) (Set, error) +func DecryptDPAPI(blob []byte) ([]byte, error) // Windows; ErrNotApplicable elsewhere +``` + +- `Locator` tells retrieval where one user data dir's keys are: the snapshot path of `Local State`, the `KeychainLabel`, the Windows `Exe` and `ABE` kind ([RFC-005](005-browser-definitions.md)), and on macOS the run's login keychain as a `LoginKeychain` — nil elsewhere, and in `restore`. The Chromium base builds it (`chromium.KeyLocator`), because only it knows the keys come from `Local State`; `app` adds the keychain. It never carries a password: only the keychain sees one ([RFC-009](009-cli-surface.md)). +- `RetrieveAll` runs this OS's retrievers in order. A retriever that doesn't apply returns `ErrNotApplicable` and is skipped. **Per version, the first key wins:** macOS's `v10` has three ordered strategies ([RFC-015](015-key-retrieval-mechanisms.md)), and once one succeeds the rest are not tried. A version's error is reported only when every retriever for it fails, so a strategy that failed before a later one succeeded is not an error. +- **Versions are independent, not a chain.** A Chrome profile upgraded past version 127 carries `v20` cookies beside `v10` passwords, so a `v20` failure keeps the `v10` key, as today. First-success across versions is the bug [RFC-015](015-key-retrieval-mechanisms.md) records as issue #578. +- **The macOS keychain retriever follows the handle.** With no keychain, or a locked one, it returns `ErrNotApplicable` and the next `v10` retriever runs — as today, where an empty or rejected password keeps that retriever out of the chain. The reason is reported once, through `Keychain.Err`, not once per browser. A label missing from an open keychain is an error, reported only if every `v10` retriever fails. The retriever that runs the `security` command asks the system service instead of reading the file, so it stays separate, with its own per-label cache. + +### Laziness + +`app` backs `ProfileSnapshot.MasterKeys` ([RFC-003](003-core-types.md)) with a per-user-data-dir call-once that asks the Chromium base for the dir's `Locator` and runs `RetrieveAll`; it keeps the retrieval error, which is reported once as the dir's `error` result, and every extraction in the dir gets whatever keys were found. The login keychain carries its own once: on macOS `app` builds it without opening it (a build-tagged one-liner), and its first query opens it and calls the `PasswordFunc` — the only step that can prompt. Go 1.20 has no `sync.OnceValues`, so each is a `sync.Once` with its stored result. The first extractor that needs cleartext triggers them; a run that only touches non-secret data never does, so it never prompts and never performs a privileged lookup. Today the macOS password is resolved as soon as any Chromium or Safari browser is discovered, and Chromium's `Extract` retrieves keys before it looks at the categories — so `dump -b chrome -c history` prompts. The lazy handles design that out. + +## Decryption dispatch + +Chromium's blob format belongs to the Chromium base, so its dispatch lives there. The version prefix picks the key from the `Set`: `v10`, `v11`, and `v20` decrypt with their version's key; `v12` is recognized and reported as unsupported, as today; a blob without a prefix goes to `masterkey.DecryptDPAPI`. The key length picks the cipher — 32 bytes means AES-GCM (Windows), 16 bytes means AES-CBC (macOS, Linux). Yandex's format (per-row AAD, a wrapped data key) is handled by its override with the same primitives. + +Choosing the cipher from the key at runtime, rather than from `GOOS` at build time, is what makes **cross-host decryption** work: a `keys.json` and an archive taken on the same machine can be decrypted on any OS ([RFC-009](009-cli-surface.md)). The keys belong to the user data dir they were taken from; they do not decrypt another machine's data. + +## Firefox and Safari + +Firefox doesn't use an OS secret store the way Chromium does: its key is derived from the profile's own `key4.db` with the NSS primitives in `crypto`, inside `internal/browser/firefox`, and checked against `logins.json` to pick the right candidate. Everything it needs is in the snapshot. + +Safari's passwords live in the login keychain. The Safari password extractor reads them through the run's `keychain.Keychain`, which `safari.Extractors` captures for the default profile only: the keychain belongs to the user, so attributing it to every profile would duplicate its entries. Without a usable password the keychain stays locked and the extractor exports metadata only, as today. + +The keychain is not a snapshot source. It is not a browser file and lies outside every Chromium user data dir; it lives for the run, while a snapshot lives for one user data dir, so a copy in Safari's snapshot could not serve Chromium; and a copy would put one more sensitive file on disk. The handle reads the file once, when it opens — the stable bytes the snapshot rule is for. + +## What stays out of these packages + +- No data-type knowledge. `crypto` imports nothing from the project; `masterkey` never imports `browser` or `record`. +- No orchestration. Neither decides _which_ extractions run — that's the planner. +- No logging of secrets, ever. Retrieval returns errors; the reporter decides what the operator sees, and key bytes and passwords are never in a log line. + +## Boundary with the technique RFCs + +The format and technique RFCs (013–021) remain the source of truth for mechanics (how ABE injection works, how DPAPI and the keychain are read, the Yandex specifics, the locked-file bypass). This RFC only guarantees that those mechanics sit behind `masterkey` and `crypto` and nowhere else, so the rest of the program — and the people reading it on stage — deal with a handful of clean functions, not six techniques. diff --git a/rfcs/007-cli-and-output-design.md b/rfcs/007-cli-and-output-design.md deleted file mode 100644 index 1f1172d..0000000 --- a/rfcs/007-cli-and-output-design.md +++ /dev/null @@ -1,140 +0,0 @@ -# RFC-007: CLI & Output Design - -**Author**: moonD4rk -**Status**: Living Document -**Created**: 2026-04-05 - -## 1. Command Structure - -The CLI is built on [cobra](https://github.com/spf13/cobra) with six subcommands: `dump`, `dumpkeys`, `archive`, `restore`, `list`, and `version`. - -### 1.1 Root Command - -The root command defines one persistent flag: `--verbose` / `-v` (enable debug logging). - -**Default-to-dump**: when no subcommand is given, the root delegates to `dump`. All of `dump`'s flags are copied onto the root command, so `hack-browser-data -b chrome` and `hack-browser-data dump -b chrome` are equivalent. - -### 1.2 dump Command - -The primary command. Extracts, decrypts, and writes browser data to files. - -| Flag | Short | Default | Description | -|------|-------|---------|-------------| -| `--browser` | `-b` | `"all"` | Target browser | -| `--category` | `-c` | `"all"` | Data categories (comma-separated) | -| `--format` | `-f` | `"json"` | Output format: csv, json, cookie-editor | -| `--dir` | `-d` | `"results"` | Output directory | -| `--profile-path` | `-p` | | Custom profile directory | -| `--keychain-pw` | | | macOS keychain password | -| `--zip` | | `false` | Compress output to zip | - -**Workflow**: DiscoverBrowsersWithKeys (filter by `-b`) → parseCategories (split `-c` on commas) → NewWriter (select formatter by `-f`) → Extract loop (each browser) → Write → optional CompressDir. - -The nine recognized categories are: `password`, `cookie`, `bookmark`, `history`, `download`, `creditcard`, `extension`, `localstorage`, `sessionstorage`. The string `"all"` maps to all nine. - -### 1.3 list Command - -Lists all detected browsers and profiles via `text/tabwriter`. - -**Basic mode** (default) — three columns: Browser, Profile, Path. - -**Detail mode** (`--detail`) — adds a column for every category showing entry counts. This calls `CountEntries()` on each browser (not `Extract()`) — no decryption is performed. - -### 1.4 version Command - -Prints version, commit hash (truncated to 8 chars), and build date. Values are injected at build time via `-ldflags`. When building without ldflags (development mode), falls back to `runtime/debug.ReadBuildInfo()` to extract `vcs.revision` and `vcs.time`. - -## 2. Output Architecture - -All output logic lives in the `output` package. Only one type is exported: `Writer`. - -### 2.1 Writer - -Three methods define the entire API: - -- **`NewWriter(dir, format)`** — creates a writer with the specified formatter -- **`Add(browser, profile, data)`** — accumulates one browser profile's extraction results -- **`Write()`** — aggregates all results by category and writes each non-empty category to its own file - -### 2.2 Row Type - -An unexported `row` wraps any entry struct with browser and profile context. It provides CSV header/value generation via reflection on `csv` struct tags, and flat JSON output via `reflect.StructOf` dynamic struct building (browser + profile fields prepended to entry fields). - -### 2.3 Formatter Interface - -An unexported interface with two methods: `format(w, rows)` and `ext()` (file extension). - -| Format | Extension | Description | -|--------|-----------|-------------| -| `csv` | `.csv` | Standard `encoding/csv`, reflection-based headers from `csv` struct tags | -| `json` | `.json` | `json.Encoder` with indent, no HTML escape, flat objects | -| `cookie-editor` | `.json` | CookieEditor-compatible format, non-cookie categories fall back to standard JSON | - -## 3. Output Formats - -### 3.1 CSV - -Headers and values are extracted via reflection on the `csv` struct tag of each entry field. A UTF-8 BOM (`0xEF 0xBB 0xBF`) is prepended for Excel compatibility. Field types are converted to strings: `time.Time` → RFC3339, `bool` → `"true"`/`"false"`, integers → base-10 string. - -### 3.2 JSON - -Each row is serialized via `MarshalJSON()`, which uses `reflect.StructOf` to dynamically build a flat struct at runtime — browser and profile are top-level fields alongside the entry fields, avoiding nested JSON. The encoder uses two-space indent and disables HTML escaping to preserve URLs. - -### 3.3 CookieEditor - -Produces JSON compatible with the [CookieEditor](https://cookie-editor.cgagnier.ca/) browser extension. Cookie entries are converted to a specific field mapping: - -| CookieEntry field | CookieEditor field | Notes | -|-------------------|--------------------|-------| -| Host | domain | | -| Path | path | | -| Name | name | | -| Value | value | | -| IsSecure | secure | | -| IsHTTPOnly | httpOnly | | -| ExpireAt | expirationDate | Unix timestamp as float64 | - -Non-cookie categories fall back to the standard JSON formatter. - -## 4. File Organization - -Output follows a **one file per category** convention: - -``` -results/ -├── password.csv -├── cookie.csv -├── history.csv -├── bookmark.csv -├── download.csv -├── creditcard.csv -├── extension.csv -├── localstorage.csv -└── sessionstorage.csv -``` - -Data from all browser profiles is aggregated into the same file. The `browser` and `profile` columns identify which browser and profile each row came from. Empty categories produce no file. - -File permissions are restrictive: directories `0750`, files `0600` (data may contain passwords and cookies). - -## 5. Data Flow - -``` -CLI: hack-browser-data dump -b chrome -c password,cookie -f csv -d results - → DiscoverBrowsersWithKeys(name="chrome") → []Browser - → parseCategories("password,cookie") → []Category - → NewWriter("results", "csv") → *Writer - → for each browser: - Extract(categories) → []ExtractResult - Writer.Add(browser, profile, data) - → Writer.Write() - → aggregate by category → format rows → write files - → (optional) CompressDir → results.zip -``` - -## Related RFCs - -| RFC | Topic | -|-----|-------| -| [RFC-001](001-project-architecture.md) | Browser interface and Extract() orchestration | -| [RFC-008](008-file-acquisition-and-platform-quirks.md) | File utilities (CompressDir) | diff --git a/rfcs/007-snapshot-and-acquisition.md b/rfcs/007-snapshot-and-acquisition.md new file mode 100644 index 0000000..a859832 --- /dev/null +++ b/rfcs/007-snapshot-and-acquisition.md @@ -0,0 +1,79 @@ +# RFC-007: Snapshot & Acquisition + +## The snapshot-first rule + +No parser ever reads a live browser profile. Capture copies the files a plan needs into a **snapshot directory** — one snapshot per user data dir — and every extractor reads only from its user data dir's snapshot, through the `ProfileSnapshot` that wraps it. Today's code already does this per profile (`filemanager.Session` copies sources into a temp directory before parsing); the rewrite makes it one stage with one contract, so: + +- A running browser holds files open and mutates them mid-read. The snapshot is a point-in-time copy; parsers see stable bytes. +- Locked-file handling (a Windows reality) stays in one place — the snapshot's copier — and every acquisition path uses it. +- `archive` and `restore` are not special modes: `archive` is "capture, then zip the snapshot directory", `restore` is "unzip or open a snapshot directory, then extract from it". Same code path. + +## Contract + +```go +type File struct { + DirID string // the user data dir's ID; also the snapshot it lands in + From string // absolute path of the user data dir it is copied from + Rel string // slash-separated path relative to From, and to the snapshot + IsDir bool +} + +type Dir struct{ /* unexported */ } + +func Temp() (*Dir, error) // a new temporary snapshot directory, mode 0700 +func Open(path string) (*Dir, error) // an existing one, used in place +func Unzip(src string) (*Dir, error) // into a temporary snapshot directory + +func (d *Dir) Capture(ctx context.Context, files []File) error +func (d *Dir) Snapshot(dirID string) Snapshot // one user data dir's snapshot +func (d *Dir) Zip(dst string) error // archive transport +func (d *Dir) Close() error + +type Snapshot struct{ /* unexported */ } + +func (s Snapshot) Path(rel string) (string, error) // absolute path inside the snapshot +``` + +`Snapshot` returns real paths, not readers: `modernc.org/sqlite` and `goleveldb` open files by path, and SQLite reads its `-wal` file from beside the database. A zip can't serve either, so the snapshot is always a directory and zip is only how it travels — today's `restore` already unzips into a temp directory first, and that stays. + +**Errors.** `Capture` keeps going when one file fails; it returns an error only when it cannot go on — a cancelled context, an unwritable snapshot directory. A file that vanished before Capture reached it reads back from `Snapshot.Path` as `fs.ErrNotExist`, which makes its extraction `absent`; a file whose copy failed reads back as that copy's error, which makes its extraction `error`. Every other extraction runs. + +## Lifetime + +`dump` captures one user data dir at a time ([RFC-001](001-architecture-and-pipeline.md)): `Execute` creates a `Temp` snapshot directory for the dir, captures its files, runs its extractions, and `Close`s it before the next dir. At most one user data dir's copies of `Login Data`, `Cookies`, and the like exist at once — close to today's per-profile session, and far from a run-long snapshot directory holding every browser's copies until the end. `archive` captures every user data dir into one snapshot directory, because the zip of that directory is its product. `restore --data-zip` unzips into a `Temp` snapshot directory; `restore --data-dir` `Open`s the given directory, which `Close` leaves in place. + +Because it holds those copies, a temporary snapshot directory is created with mode `0700` and always removed — on success, on error, and on cancellation (the run's context is cancelled on Ctrl-C). The live profile still exists, so removing the copy never loses anything. + +## Layout and user data dir identity + +A snapshot directory is `//`: one subdirectory, one snapshot, per user data dir. For the first user data dir of a browser the ID is its `Def.ID`, so the layout is exactly today's archive layout (`/`) and v1.1.0's `restore` reads new archives unchanged. A second one of the same browser — the second of Arc's two MSIX packages on Windows — gets `arc-2/`, where today's archive keys every file by browser key alone and silently drops it. + +An archive captures what today's does — `Local State` and each profile's `Preferences` marker (both named by the Chromium base, [RFC-005](005-browser-definitions.md)), the requested categories' sources, and the account-synced `Login Data For Account` — so a reader without the manifest can still find every profile. + +`keys.json` joins to the archive by the vault's `browser` key, as today. A vault for a second user data dir carries an extra optional `id` field (`"arc-2"`) — the `DirID` on the wire, per the wire-name rule; readers that don't know the field, including v1.1.0, ignore it and restore the first one, as they do today. The dump version stays `"2"`. + +## Manifest + +A new snapshot directory carries `manifest.json` at its root: a schema version, and per user data dir its ID, `Def.ID`, `Base`, profiles, and captured paths. `restore` uses it, when present, to rebuild user data dirs and profiles without re-discovering anything — that is its `Discovery` ([RFC-003](003-core-types.md)) — and then runs Extract → Export → Report exactly as a live run would. Archives without a manifest — every archive made before the rewrite — still restore through today's path: the keys.json vaults plus the directory layout. v1.1.0 ignores the extra file. + +## Copy semantics + +- Capture only ever **reads** the browser's files; it never deletes or moves anything in a real profile. +- A file is copied together with its SQLite `-wal` and `-shm` sidecars when they exist; a directory (LevelDB, Session Storage) is copied whole, skipping its `LOCK` file — both as today. +- Chromium databases are opened as copied, `-wal` included; Firefox and Safari databases are opened with `journal_mode=off` — both as today. +- `Zip` writes to a temp file beside the target and renames it into place only after the zip is closed; a failed archive leaves no partial file behind. +- `Unzip` rejects any entry whose path would land outside the snapshot directory. + +The `--zip` output-packing bug (originals deleted before the zip is written) is an Export concern and is fixed there ([RFC-008](008-output-and-export.md)). + +## Locked-file handling + +Chromium on Windows has held `Cookies` under an exclusive lock since Chrome 114, so a plain copy fails while the browser runs; on macOS and Linux file locks are advisory and never block a reader. Reading such a file is Windows-specific and lives in `winapi` (the technique itself is documented in [RFC-021](021-windows-locked-file-bypass.md)). The snapshot's copier tries a plain copy first and, on Windows only, falls back to the locked-file copy when the plain copy fails — today's order. macOS and Linux use the plain copy. Extractors are unaware of which strategy ran. + +## Scope + +`archive`, `dumpkeys`, and `restore` stay Chromium-only, as today: Firefox and Safari have no portable key in `keys.json`. Archiving them is DEFERRED; it would add capability, which this rewrite does not. + +## Why this is worth a dedicated stage + +Acquisition is where the messiest real-world facts live: files that move, lock, or vanish between discovery and read. Isolating all of that in Capture, behind a read-only `Snapshot`, means the parsers downstream are pure file-in/record-out functions. That is the difference between a parser you can unit-test with a fixture file and one that needs a live browser to exercise. diff --git a/rfcs/008-file-acquisition-and-platform-quirks.md b/rfcs/008-file-acquisition-and-platform-quirks.md deleted file mode 100644 index 65d1388..0000000 --- a/rfcs/008-file-acquisition-and-platform-quirks.md +++ /dev/null @@ -1,96 +0,0 @@ -# RFC-008: File Acquisition & Platform Quirks - -**Author**: moonD4rk -**Status**: Living Document -**Created**: 2026-04-05 - -## 1. Overview - -Browsers keep their data files open and often locked while running. Chromium on Windows is particularly aggressive: it holds exclusive locks on databases like `Cookies` via `PRAGMA locking_mode=EXCLUSIVE`. Even on macOS and Linux, reading directly from a live database can produce corrupt or inconsistent results. - -The solution is a **copy-then-read** strategy: copy all needed files to an isolated temporary directory, then extract data from the copies. The `filemanager` package manages this lifecycle, while platform-specific fallbacks handle locked files on Windows. - -## 2. Session Management - -A `Session` wraps a single temporary directory for one browser profile extraction run: - -1. **Create** — `NewSession()` creates a unique temp directory via `os.MkdirTemp("", "hbd-*")` -2. **Acquire** — `Acquire(src, dst, isDir)` copies a browser file or directory into the session -3. **Cleanup** — removes the entire temp directory tree, always called with `defer` - -## 3. Acquire Flow - -`Acquire` is the single entry point for copying browser files: - -``` -Acquire(src, dst, isDir) - ├── isDir=true → copyDir(src, dst, skip="lock") - │ - └── isDir=false → copyFile(src, dst) - ├── success ──┐ - └── failure + Windows → copyLocked(src, dst) - └── success ──┐ - copy -wal and -shm companions if present -``` - -### SQLite Companion Files - -SQLite databases using WAL mode maintain `-wal` (write-ahead log) and `-shm` (shared memory) files. After a successful file copy, `Acquire` automatically copies these companions if they exist. Without the WAL file, recently written data (cookies set in the last few seconds) would be missing. - -## 4. File Deduplication - -Multiple categories can share the same source file: - -| Engine | Categories | Shared Source | -|--------|-----------|---------------| -| Chromium | History + Download | `History` | -| Firefox | History + Download + Bookmark | `places.sqlite` | - -Each category gets its own destination path in the temp directory, so the same source file may be copied multiple times. This is intentional — each extract function expects its own independent file path, and the copy cost is negligible for small SQLite files. - -## 5. Windows Locked File Handling - -Chromium on Windows holds exclusive locks on certain databases (notably `Cookies`), causing standard file reads to fail. Chrome introduced `PRAGMA locking_mode=EXCLUSIVE` for the cookies database starting from Chrome 114 (2023) via the "Lock profile cookie files on disk" feature, preventing external processes from reading cookie data while the browser is running. This is a Windows-specific problem — macOS and Linux use `fcntl`/`flock` advisory locks that do not prevent reading by other processes. - -A dedicated technique using Windows kernel APIs (DuplicateHandle + memory-mapped I/O) is used to bypass these locks. See [RFC-009](009-windows-locked-file-bypass.md) for the full technical details. - -## 6. LevelDB Directory Handling - -Chromium stores localStorage and sessionStorage as LevelDB directories: - -| Category | Path | Type | -|----------|------|------| -| LocalStorage | `Local Storage/leveldb/` | directory | -| SessionStorage | `Session Storage/` | directory | - -When `isDir=true`, `Acquire` copies the entire directory while **skipping the `LOCK` file**. LevelDB uses this file for single-process access control; copying it could interfere with the running browser. - -## 7. SQLite Query Helpers - -### QuerySQLite - -Encapsulates the common SQLite extraction pattern: validate file exists → open database → optional `PRAGMA journal_mode=off` → execute query → iterate rows with error-tolerant scan callback. - -Row-level scan errors are logged and skipped (graceful degradation for corrupt records), while database-level errors abort the query. - -### QueryRows[T] - -A generic wrapper (Go 1.18+) that collects results into a typed slice, eliminating boilerplate. Each extract function only needs to provide the scan function. - -### Firefox journal_mode=off - -All Firefox extract calls use `journal_mode=off`. Firefox databases use WAL mode in production, and the `modernc.org/sqlite` driver may attempt WAL replay on a temp copy. Disabling the journal prevents this and treats the database as a read-only snapshot. - -Chromium extract calls do **not** disable journal mode because `Acquire` already copies the WAL/SHM companions, giving SQLite everything it needs for a clean WAL replay. - -## 8. File Utilities - -- **CompressDir** — compresses all files in the output directory into a single `.zip` file (used by `--zip` flag). Original files are removed after archiving. - -## Related RFCs - -| RFC | Topic | -|-----|-------| -| [RFC-002](002-chromium-data-storage.md) | Chromium data file locations | -| [RFC-004](004-firefox-data-storage.md) | Firefox data file locations | -| [RFC-009](009-windows-locked-file-bypass.md) | Windows locked file bypass technique | diff --git a/rfcs/008-output-and-export.md b/rfcs/008-output-and-export.md new file mode 100644 index 0000000..c519b69 --- /dev/null +++ b/rfcs/008-output-and-export.md @@ -0,0 +1,81 @@ +# RFC-008: Output & Export + +Everything a user can see in the output — file names, formats, field names, stamp values — is frozen by the compatibility contract ([RFC-000](000-goals-and-constraints.md)). This RFC describes how the rewrite reproduces it byte for byte, and the few places where today's output is wrong and gets fixed. + +## Contract + +```go +type Format int // the -f value; the zero value is JSON, the default + +const ( + JSON Format = iota + CSV + CookieEditor +) + +func ParseFormat(s string) (Format, error) // "json", "csv", "cookie-editor" + +type Writer struct{ /* unexported */ } + +func NewWriter(dir string, f Format, zip bool) (*Writer, error) +func (w *Writer) Write(c category.Category, records []record.Record) error // one extraction's records, appended in plan order +func (w *Writer) Close() error // finishes every file; with --zip, packs them +``` + +Export writes one file per non-empty category: `password.csv`, `cookie.json`, and so on — `.`, where the extension is `csv` or `json` (`cookie-editor` writes `.json`). A category with no records produces no file. The output directory is created with mode `0750` and each file with `0600`, as today. One `-f` value per run, as today. + +## Formats + +- **`json`** (default) — one array of objects per category, two-space indent, UTF-8 without a BOM. Strings keep today's HTML escaping: `&`, `<`, and `>` are written as `\u0026`, `\u003c`, and `\u003e`. Today's per-row `MarshalJSON` calls `json.Marshal`, which escapes them even though the outer encoder turns escaping off; the new records are plain structs, so the encoder leaves escaping on to produce the same bytes. Any URL with a query string shows the difference, so the parity suite catches a slip at once. +- **`csv`** — a header row, then one row per record; UTF-8 with a 3-byte BOM so Excel reads non-ASCII correctly; times in RFC 3339 (empty when zero), booleans as `true` / `false`. +- **`cookie-editor`** — cookies as the Cookie-Editor extension's import array (`expirationDate`, `httpOnly`, `hostOnly`, `sameSite`, …), written without HTML escaping, as today; every other category falls back to the `json` encoder above, which is what today's code does. + +Adding a format later is a new `Format` value and a new encoder; nothing else in the pipeline changes. + +## Wire names follow Go names (DECIDED) + +JSON keys and CSV headers are the snake_case form of the Go field names: `Cookie.IsHTTPOnly` is `is_http_only`, `Extension.HomepageURL` is `homepage_url`. `encoding/json` does not derive names on its own, so every field keeps an explicit `json` and `csv` tag, and the rule "tag = snake_case(field name)" is enforced by `tagliatelle` (`use-field-name: true`, `json: snake`, `csv: snake`). Today's record and `keys.json` types already pass that check unchanged; the Cookie-Editor encoder is exempt, because its keys are the extension's import schema, not ours. + +The consequence is stated plainly: since the output is frozen, **the record field names are frozen too** — a rename would change a column. A field can only be renamed together with a deliberate, announced output change, and the lint makes such a change impossible to miss in review. + +### Source stamp + +Every record starts with two flat source fields — `Browser` and `Profile` ([RFC-003](003-core-types.md)) — serialized as the leading `browser` and `profile` keys in JSON and the leading columns in CSV, exactly as today. `browser` is the display name (`Chrome`, `Microsoft Edge`); `profile` is the profile name (`Default`, `Profile 1`, a Safari profile's title), never a path. The pipeline's `Collector` sets both through `record.Stamp`, so no extractor can leave them out. + +## Deterministic ordering + +Output order is defined once per category, in the exporter, for every browser. Files list extractions in plan order — the browser table's order (one merged list whose per-OS projections equal today's `platformBrowsers()` orders), then user data dir ID, then profiles in discovery order (directory order for Chromium and Firefox, the default profile first for Safari) — which matches today's order. Within an extraction, records are sorted by today's key, with tie-breakers added and a stable sort (`sort.SliceStable`; Go 1.20 has no `slices`), so two runs over the same snapshot produce byte-identical files: + +| Category | Order | +| --------------------------------------------------- | -------------------------------------------------------------------------------------- | +| password | `created_at` descending, then `store` (local before account), `url`, `username` | +| cookie | `created_at` descending, then `host`, `name`, `path` | +| history | `visit_count` descending, then `last_visit` descending, `url` | +| download | `start_time` descending, then `url` | +| bookmark | `created_at` descending, then `id` ascending | +| creditcard, extension, localstorage, sessionstorage | source order, made explicit (`ORDER BY rowid`, LevelDB key order, JSON document order) | + +Today the order is decided in each extractor with an unstable `sort.Slice`, so ties come out in arbitrary order — and Firefox history sorts _ascending_ by visit count (`browser/firefox/extract_history.go`) while Chromium and Safari sort descending. The table above keeps today's keys and fixes Firefox to match the others. + +## Streaming vs. buffering + +Extractors emit records one at a time ([RFC-003](003-core-types.md)), but sorting needs an extraction's full set. The writer buffers one extraction's records, sorts them, appends them to that category's file, and releases them — memory is bounded by the largest single category of a single profile, where today's writer holds the whole run. The standard encoder cannot append to an open array, so the writer frames it itself: `[` before the first element, each element encoded with a two-space prefix and indent, `,` between elements, and `]` plus a newline on `Close`. Those are the bytes a single `Encode` of the whole slice produces, and the parity suite proves it ([RFC-011](011-testing-and-quality.md)). + +## `--zip` + +`--zip` keeps today's result — `/.zip` with the files at its top level, and the loose files removed — but fixes the order. Today `fileutil.CompressDir` deletes each file as soon as it is added to an in-memory zip and writes the zip to disk last, so any failure along the way loses the output. The rewrite writes the zip to a temp file, closes and renames it into place, and only then deletes the originals; a failure leaves every output file where it was. + +## Output fixes (listed exceptions to "unchanged") + +- **Firefox history order** — `visit_count` descending, like Chromium and Safari. +- **Firefox bookmarks** — `folder` holds the real folder name instead of `url`, and `type` and `id` are filled; today they are always `url`, empty, and `0`. +- **Safari bookmark IDs** — unique across the whole bookmark tree; today each ID is the index among its siblings, so IDs repeat across folders. +- **`browser` in `restore` output** — the display name (`Chrome`), as `dump` writes it; today `restore` writes the vault key (`chrome`). + +## Secrets in output + +`-c all` is the default, as today, so a bare run exports every category, passwords and cookies included. The exporter does not redact: what reaches Export was asked for. + +## DEFERRED + +- **JSON without HTML escaping.** Every JSON parser reads `\u0026` and `&` as the same string, but dropping the escapes would change bytes in nearly every file, so it waits for an announced output change. diff --git a/rfcs/009-cli-surface.md b/rfcs/009-cli-surface.md new file mode 100644 index 0000000..d405524 --- /dev/null +++ b/rfcs/009-cli-surface.md @@ -0,0 +1,79 @@ +# RFC-009: CLI Surface + +The command surface is v1.1.0's, unchanged: the operator's view is the spec, and the architecture is derived backward from it. This RFC records that surface, the one additive input the rewrite introduces, and the behavior fixes behind unchanged flags. + +## Commands (unchanged) + +| Command | Does | Flags | +| ---------- | -------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| `dump` | Discover → extract → export. The default command. | `-b` `-c` `-f` `-d` `-p` `--keychain-pw` `--zip` | +| `dumpkeys` | Write Chromium master keys as `keys.json` (stdout by default; `-o` writes the file with mode `0600`). | `-b` `-o` `--keychain-pw` | +| `archive` | Zip the decryption-relevant Chromium files for another host. | `-b` `-c` `-o` (default `browser-data.zip`) | +| `restore` | Decrypt an archive or copied data with a `keys.json`. | `--keys` (required, `-` = stdin), `--data-dir` \| `--data-zip` (exactly one), `-b` `-c` `-f` `-d` `--zip` | +| `list` | Show detected browsers and profiles (columns Browser, Profile, Path); `--detail` adds a count column per category. | `--detail` | +| `version` | Version, commit (first 8 characters), and build date, set by `-ldflags`; a build without them reads the module's VCS build info. | — | + +`-v, --verbose` is global. `hack-browser-data` with no subcommand runs `dump`, and `dump`'s flags are mirrored onto the root, so `hack-browser-data -b chrome` keeps working (this also covers the Windows double-click case). + +Every command is a different cut of one pipeline ([RFC-001](001-architecture-and-pipeline.md)): `list` stops after Plan; `list --detail` runs Extract with no secrets and counts what the `Collector` receives instead of exporting it; `archive` captures every user data dir into one snapshot directory and zips it; `dumpkeys` captures each user data dir's `Local State` and runs only key retrieval; and `restore` extracts from an existing snapshot directory. + +## Core flags of `dump` (unchanged) + +| Flag | Default | Meaning | +| -------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `-b, --browser` | `all` | `all` or one ID from `browser.Supported()`, this OS's rows | +| `-c, --category` | `all` | comma-separated categories: `password`, `cookie`, `bookmark`, `history`, `download`, `creditcard`, `extension`, `localstorage`, `sessionstorage` | +| `-f, --format` | `json` | `csv`, `json`, or `cookie-editor` | +| `-d, --dir` | `results` | output directory | +| `-p, --profile-path` | — | custom data location for one browser (the path `chrome://version` shows, or a user data dir) | +| `--keychain-pw` | — | macOS login password (kept for compatibility; visible in `ps` and shell history) | +| `--zip` | `false` | pack the output files into a zip | + +The flag names stay, and the Go names follow them: `-c/--category` selects `category.Category` values ([RFC-004](004-naming-decisions.md)). What is frozen is each flag's name, shorthand, type, and default; usage strings may be clarified — `--keychain-pw` gains a note that it is visible in `ps` — and the root command's description gains Safari, which today it omits. `-b`'s usage string lists the running OS's IDs, as today. + +## Validation happens first — the ordering bug, designed out + +Today `-c` and `-f` are checked only after discovery and after the keychain prompt (`cmd/hack-browser-data/dump.go`, `extract.go`), so a typo in a format wastes a prompt and a discovery pass. In the rewrite, **Validate is stage 1** ([RFC-001](001-architecture-and-pipeline.md)): an unknown format, category, or browser ID, a `-d` that cannot be created, `--data-dir` together with `--data-zip`, or an unreadable `--keys` all fail before any browser is touched and before any secret is read. The exit status stays today's `1`; only the timing changes. The rule: _nothing with a side effect runs until the request is valid._ + +## `-p, --profile-path` — same meaning, the long-standing bugs fixed + +The flag keeps its meaning and its name: a custom data location for one browser. It has never worked well, and the rewrite fixes every known fault behind it without changing the flag. + +- **Validated first.** Today a non-existent `-p` is read as an empty directory, so the run just says "no browsers found" and exits `0`. Validate now checks that the path exists and is a directory, and exits `1` with a clear message if not ([RFC-001](001-architecture-and-pipeline.md)). +- **With `-b all`.** Today `-p` is silently ignored when `-b` is `all` (`browser/browser.go`, `discoverFromConfigs`), because the override is guarded by `name != "all"`. Validate now logs a warning that `-p` needs a specific `-b`, then ignores it as before — the run itself is unchanged. Rejecting the combination would turn today's exit status `0` into `1`, which the contract rules out. +- **Pointing at a Chromium profile directory.** The help text asks for the path `chrome://version` shows, which is a profile directory (`…/User Data/Default`). Today that directory becomes the whole user data dir, so the `Local State` one level up is never found and, on Windows, the DPAPI and ABE keys cannot be derived — `-p` effectively cannot decrypt anything there. The Chromium `Discover` now looks at what it was given: a directory holding `Preferences` is a profile, so its parent is the user data dir and only that profile is selected; a directory holding profile subdirectories is a user data dir, as before. Either way the keys resolve. +- **Firefox selects only the named profile.** Today the Firefox override takes the parent of the given directory as the Profiles root and then exports _every_ profile under it, not the one asked for. `Discover` now selects only the profile the path names. This narrows today's output for `-b firefox -p ` and is called out as an expected diff in the parity suite ([RFC-011](011-testing-and-quality.md)). +- **Safari says no.** `-b safari -p` is rejected in Validate with a one-line reason: Safari's data is spread across `~/Library` and a container, so a single profile directory cannot stand in for it. Today the flag is quietly accepted and has no effect. + +Selecting profiles by name across browsers is DEFERRED; if added, it gets its own flag rather than changing `-p`. + +## Keychain password input (DECIDED) + +`--keychain-pw` stays, because scripts use it. One safer input is added beside it: + +- `--keychain-pw-stdin` (on `dump` and `dumpkeys`): read the password from the first line of standard input, for piping from a secret manager. + +Precedence, highest first: + +1. An explicit flag — `--keychain-pw` or `--keychain-pw-stdin` (mutually exclusive). +2. An interactive no-echo prompt (`golang.org/x/term`), only when stdin is a terminal. +3. None: keychain-protected data is exported as metadata only, as today. + +Explicit inputs win because they are the user's stated intent; the prompt is the fallback, never the first step. Validate turns the chosen input into the one `keychain.PasswordFunc` the run's login keychain is built with ([RFC-003](003-core-types.md)); no other code sees the password. The function runs when the keychain is first used, so `dump -c history` never asks ([RFC-006](006-key-retrieval-and-crypto.md)). Opening the keychain is the check: a missing or wrong password leaves it locked, keychain-protected data is exported as metadata only, as today, and the reason is reported once. The help text says what each input exposes: `--keychain-pw` is visible in `ps` and shell history; stdin from a secret manager leaves no trace. + +There is no environment variable. Every child process the tool starts would inherit it — the macOS key retrieval runs the `security` command — and the inline form `VAR=… hack-browser-data` lands in shell history just like the flag. A second non-interactive input would add only a precedence level and its tests. + +## Reporting & exit status + +After a run, the reporter prints a per-browser, per-profile, per-category summary with each extraction's outcome and count on stderr, after today's "Exported to …" lines. The summary is additive and not part of the contract. `-v` adds record-level debug lines, as today. The exit status is today's: `0` when the run completes, whatever the per-extraction outcomes, and `1` when it cannot start or finish ([RFC-001](001-architecture-and-pipeline.md)). + +## `restore` specifics (unchanged) + +`restore`'s universe is its `keys.json`, not the local table: `-b` filters the dump's vaults, and a vault's `Def` is resolved with `browser.Lookup`, which searches the whole table whatever the host OS ([RFC-005](005-browser-definitions.md)), so a Windows-only fork restores on macOS. Exactly one of `--data-dir` and `--data-zip` is required. A zip is extracted into a temporary snapshot directory (`snapshot.Unzip`), rejecting entries that escape it, and removed when the run ends; a `--data-dir` is opened in place (`snapshot.Open`) and never removed ([RFC-007](007-snapshot-and-acquisition.md)). The data has two layouts, as today: `/` subdirectories (the archive layout), from which every selected vault restores, or one browser's hand-copied `User Data`, which is unambiguous only when `-b` selects a single vault. + +## DEFERRED + +- Profile selection by name. +- More than one `-f` value per run. +- Machine-readable exit codes for usage errors and partial runs (opt-in only, if ever). +- A `--quiet` switch for the summary. diff --git a/rfcs/010-dependencies.md b/rfcs/010-dependencies.md new file mode 100644 index 0000000..e774032 --- /dev/null +++ b/rfcs/010-dependencies.md @@ -0,0 +1,44 @@ +# RFC-010: Dependencies + +Every dependency is justified or dropped. The bar: a dependency earns its place only if replacing it with stdlib would cost materially more than the dependency costs us (in audit surface, license, and Go-1.20 compatibility). The tool runs on evidence machines and goes on stage — the dependency list is part of the audit story. + +## Direct dependencies — keep / drop / pin + +| Module | Decision | Rationale | +| ------------------------------------------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `modernc.org/sqlite` v1.31.1 | **KEEP, pinned** | Pure-Go SQLite; no cgo, so cross-compilation stays trivial. v1.32+ needs Go 1.21. Wrapped by `internal/sqlitex`. | +| `github.com/spf13/cobra` + `pflag` | **KEEP** | Command tree and flags; the frozen CLI surface is defined with them. Confined to `cmd/`. | +| `github.com/inconshreveable/mousetrap` | **KEEP** | Detects a launch from Explorer (double-click) so `cmd/` can hide the console and skip cobra's double-click guard; already required by cobra. | +| `github.com/tidwall/gjson` v1.18.0 | **KEEP, pinned** | Read-only JSON probing of browser files (`Local State`, `Bookmarks`, `Secure Preferences`) without full unmarshal. v1.19+ needs Go 1.23. | +| `github.com/syndtr/goleveldb` | **KEEP** | LevelDB reader for Local/Session Storage. No stdlib equivalent. | +| `github.com/moond4rk/binarycookies` | **KEEP** | First-party; Safari cookie format. MIT. | +| `github.com/moond4rk/plist` | **KEEP** | First-party fork of `howett.net/plist`; Safari plists. BSD-3 — keep Howett's notice. | +| `github.com/moond4rk/keychainbreaker` | **KEEP** | First-party; macOS keychain files. Apache-2.0. Behind `keychain` and `masterkey` (darwin); the Safari extractor uses only its record type. | +| `github.com/godbus/dbus/v5` + `ppacher/go-dbus-keyring` | **KEEP** | Linux Secret Service access. BSD. Behind `masterkey` (linux). | +| `golang.org/x/sys` v0.30.0 | **KEEP, pinned** | Windows syscalls for DPAPI, locked-file copy, and the ABE bridge. Behind `winapi` and `abe`. Later releases raise the `go` directive above 1.20. | +| `golang.org/x/term` v0.29.0 | **KEEP, pinned** | No-echo password prompt ([RFC-009](009-cli-surface.md)). v0.30+ needs Go 1.23. | +| `github.com/otiai10/copy` | **DROP** | It links `golang.org/x/sync` into every binary, and its Windows build imports `testing` and the `github.com/otiai10/mint` assertion library from non-test code, so both ship in the release exe. Every call already goes through one wrapper; a ~50-line copier in `internal/snapshot` (files, directories, skip list) replaces it. | +| `github.com/stretchr/testify` | **KEEP (test-only)** | Assertions in tests; never linked into the binary. | + +`golang.org/x/text` needs no action: HBD does not import it and it is not linked into the binary. It stays in `go.mod` as `// indirect` only because goleveldb's test dependencies require it (`go mod why -m golang.org/x/text`), so dropping it is not something HBD code can do — and the project CLAUDE.md's "x/text will be removed" note is already moot. + +## Indirect dependencies + +The `modernc.org/*` set (`libc`, `memory`, `mathutil`, …) comes in through `modernc.org/sqlite` and rides its pin. `go-humanize`, `golang-lru/v2`, `uuid`, `go-isatty`, `go-strftime`, `bigfft`, `snappy`, `tidwall/match` + `pretty`, `go.yaml.in/yaml/v3`, `x/sync`, `x/tools`, `x/text` are transitive. After dropping `otiai10/copy`, run `go mod tidy` under the Go 1.20 toolchain and confirm that `otiai10/mint` leaves the module graph and the `go` directive does not move. + +## The Go 1.20 discipline + +- `go mod tidy` and `go mod verify` must be run with the **go@1.20** toolchain (per project CLAUDE.md), or a transitive dependency silently bumps the `go` directive and breaks the Windows 7 build. +- Any candidate dependency is checked for its own `go` directive before adoption. A library requiring 1.21+ is disqualified regardless of merit. +- Dependabot's ignore rules (`.github/dependabot.yml`) hold every pin above; a new pin gets its rule in the same PR. +- CI must not follow `go.mod`. Today every workflow runs `actions/setup-go` with `go-version-file: go.mod`, so if a bump raises the `go` directive, CI installs the newer Go and passes. CI pins `go-version: '1.20.x'` instead and fails when `go.mod` says anything but `go 1.20` or gains a `toolchain` line ([RFC-011](011-testing-and-quality.md)). + +## License hygiene + +The project is MIT; the shipped binary links only permissively licensed modules. The policy is an allowlist — MIT, BSD-2-Clause, BSD-3-Clause, Apache-2.0, ISC — checked against the modules actually linked into each release binary (`go list -deps` per GOOS), and a release that links anything else fails. Today's linked set is MIT (gjson, binarycookies), BSD (modernc, goleveldb, godbus, go-dbus-keyring, plist, the `x/` modules), and Apache-2.0 (cobra, keychainbreaker). `golang-lru/v2` (MPL-2.0) is in the module graph but not linked; the check keeps it that way. + +BSD and Apache-2.0 require their notices in binary distributions, so each release archive ships a `THIRD_PARTY_NOTICES` file generated from the linked modules' license files. + +## Net effect + +Drop `otiai10/copy` (and with it `x/sync` from every binary and `testing` + `mint` from the Windows exe); make every Go-1.20 pin explicit; keep everything else. The result is a dependency list short enough to read aloud and defend — which is the goal for a showcased tool. diff --git a/rfcs/011-testing-and-quality.md b/rfcs/011-testing-and-quality.md new file mode 100644 index 0000000..19908b4 --- /dev/null +++ b/rfcs/011-testing-and-quality.md @@ -0,0 +1,96 @@ +# RFC-011: Testing & Quality + +The pipeline split ([RFC-001](001-architecture-and-pipeline.md)) exists partly so each concern can be tested in isolation, and the compatibility contract ([RFC-000](000-goals-and-constraints.md)) only holds if a test pins it. This RFC says how. + +## Test strategy by layer + +| Layer | How it's tested | +| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `crypto` primitives | Pure functions over bytes; fixed known-answer vectors. No OS, no files. | +| `category` | `String` / `Parse` round-trip over `All()`; the zero `Category` is "none". | +| `record` | `Stamp` sets `Browser` and `Profile`; every record type's tags equal snake_case(field name); each type's `Category()` matches the table in [RFC-003](003-core-types.md). | +| extractors (`browser/*`) | A sanitized fixture (SQLite, JSON, plist, LevelDB) in `testdata/`, captured into a `t.TempDir()` snapshot, parsed, and compared to a golden record set. No live browser. | +| `snapshot` | `t.TempDir()`; capture with `-wal`/`-shm` sidecars, reopen, zip round-trip, Zip-Slip rejection; a vanished file reads back as `fs.ErrNotExist` and a failed copy as its error while the rest of the capture completes; `Close` removes a temporary snapshot directory — also after an error — and leaves an opened one in place. | +| `export` | Records in → golden `csv` / `json` / `cookie-editor` out; deterministic order; byte-identical to today's encoder on the same records, HTML escaping included. | +| `app` (planner/report) | Table tests over synthetic user data dirs; asserts the `Plan` with `reflect.DeepEqual`, every outcome rule, and the exit status. | +| `masterkey` | Fake retrievers: per version the first key wins and later retrievers are not called; a version's error appears only when all its retrievers fail; a `v20` failure keeps the `v10` key. | +| platform (`winapi`, OS retrievers in `masterkey`) | `_windows_test.go` / `_darwin_test.go` / `_linux_test.go`, run on the real OS in CI; the ABE path also on a dedicated Windows host. | + +Principle: **a test needs a fixture file, not a running browser.** Because every parser reads through a `ProfileSnapshot` over a `snapshot.Snapshot`, a `testdata/` file is a complete input. This is what makes the extractor suite fast and runnable on any OS. + +## Compatibility tests + +These guard the contract; a failure means the rewrite changed something users can see. + +- **CLI surface.** For every command, the set of flags — name, shorthand, type, default — is compared against a golden captured from v1.1.0. One golden serves every OS and is checked on all three: none of these attributes varies by OS — only `-b`'s usage text does, and usage text is not recorded. Only the additive `--keychain-pw-stdin` is expected on top. +- **Output parity.** During the migration, the old and the new code paths run on the same fixture snapshots and their output directories are diffed byte for byte, for every format; the fixtures include URLs with `&` and `<`, so JSON escaping is covered. The only expected differences are the listed output fixes ([RFC-008](008-output-and-export.md)), each pinned by its own test. +- **`keys.json` and archives.** A v1.1.0 `keys.json` and archive restore with the new binary; a new `keys.json` parses with v1.1.0's reader (version `"2"`, unknown fields ignored); a new archive keeps the `/…` layout. +- **`list --detail` counts.** Counts from Extract-without-secrets equal today's per-category counts on the same fixtures. + +## Golden files + +Export and extractor tests compare against checked-in golden outputs. Deterministic ordering is what makes goldens stable — without it, goldens would flap. A `-update` flag regenerates them on intentional changes. Goldens double as documentation of the exact output shape, useful for the README and for talks. + +## Regression tests for the known bugs + +Each bug designed out by this rewrite gets a test that would have caught it, so it can never silently return: + +- **Firefox bookmark fields** (`folder` always `url`, `type` empty, `id` 0): golden assertions on a fixture with nested folders. +- **Firefox history order**: `visit_count` descending for every browser, Firefox included. +- **Safari bookmark IDs**: unique across the whole tree, not repeated per folder. +- **Arc multi-dir**: two `arc` user data dirs yield IDs `arc` and `arc-2`, distinct snapshots, and distinct `keys.json` vaults, while overrides and the vaults' `browser` key still use `arc`. +- **`--zip` data loss**: a failing zip write leaves every output file in place. +- **Late flag validation**: `-f bogus` exits `1` with no discovery call and no password resolution (both injected as spies). +- **Eager secrets**: `dump -b chrome -c history` never calls `ProfileSnapshot.MasterKeys` and never opens the login keychain: a counting fake `PasswordFunc` stays at zero. +- **JSON escaping**: a URL with `&` and `<` is written escaped in `json` and unescaped in `cookie-editor`, as today. +- **Supported browsers**: `Supported()` lists only this OS's rows, and `Lookup` finds every row, so a vault for a Windows-only fork restores on macOS. +- **macOS key order**: when the first `v10` strategy fails and a later one succeeds, the key is used and no error is reported. +- **One keychain report**: with a locked login keychain, every macOS Chromium user data dir falls through to the next `v10` retriever, and the reason is reported once for the run, not once per browser. +- **Unset outcome**: a `Result` whose outcome was never set does not report as `ok`. +- **Per-dir snapshots**: a dump over two user data dirs never has both dirs' copies on disk at once. +- **`-p` validation**: a non-existent `-p` path exits `1`, not `0` with "no browsers found". +- **`-p` with `-b all`**: a warning is logged and no user data dir is overridden. +- **`-p` at a Chromium profile directory**: its parent becomes the user data dir, so `Local State` is captured and keys resolve. +- **`-p` for Firefox**: only the named profile is exported, not every sibling under it. +- **`-p` for Safari**: rejected in Validate with a reason. +- **Keychain password precedence**: explicit flag > prompt > none. +- **Temp snapshot cleanup**: a run that fails mid-way leaves no copied `Login Data` or `Cookies` behind. +- **Discovery errors are not absence**: an unreadable user data dir (permission denied) is reported as an `error` result, distinct from one that simply isn't there (nothing). The home directory comes from `DiscoverOptions`, so a `t.TempDir()` stands in. +- **Safari discovery reads a copy**: listing Safari profiles opens a snapshot copy of `SafariTabs.db`, never the live file. + +## Table and payload consistency + +- Every key in the Chromium override table resolves through `browser.Lookup` to a Chromium `Def`. +- The table's Windows rows with `ABE` other than `ABENone` and the rows of the payload's `com_iid.c` name the same executables and ABE kinds; the test parses the C table. It lives inside `browser` and reads the whole table, since `Supported()` lists only the running OS's rows. (The Go-side `winutil.Table` join, and the `TestWinUtilTableCoversABEBrowsers` that guarded it, disappear into `Platform`.) + +## Import direction + +The table in [RFC-002](002-package-layout.md) is kept by review, not by a linter or a test: every new import edge is either in the table or added to it in the same pull request. The compiler still rejects cycles. + +## Go 1.20 pitfalls + +The `go 1.20` directive constrains more than the standard library: + +- **Loop variables are shared.** Under `go 1.20`, every closure created in a loop sees the loop variable's last value, and the per-iteration semantics of Go 1.22 apply only to modules that declare `go 1.22` or later, whatever toolchain builds them. Extractors are closures built per profile, and `go vet`'s `loopclosure` check only looks at closures started with `go`, `defer`, and the like, so it does not cover them. A two-profile fixture in every base asserts that each extraction reads its own profile's files. +- **No 1.21+ helpers.** `sync.OnceValues`, `slices`, `maps`, `cmp`, and the `min` / `max` / `clear` builtins are unavailable: the per-dir `MasterKeys` call-once and the keychain handle each hold a `sync.Once` with stored results, and sorting uses `sort.SliceStable` with a multi-key less function. + +## Tooling + +- **golangci-lint v2** — the project's existing config, extended with `tagliatelle` (`case.use-field-name: true`, `case.rules: {json: snake, csv: snake}`) on the packages that own a wire format — `record`, `masterkey` (`keys.json`), and `snapshot` (`manifest.json`); the Cookie-Editor encoder and any struct that mirrors a browser's own file format stay outside it. `lll` stays at 140. +- **gofumpt** + **goimports** with `-local github.com/moond4rk/hackbrowserdata`. +- **CI matrix**: Go pinned to `1.20.x` (not `go-version-file`) on Windows, macOS, and Linux; build + vet + lint + test; a step that fails unless `go.mod` says `go 1.20` with no `toolchain` line. The Windows ABE path is additionally validated on a dedicated Windows host against the current cookie/key baseline, not in hosted CI. + +## Doc hygiene + +The project CLAUDE.md is updated as part of the migration ([RFC-012](012-migration-roadmap.md)): + +- it references `go-sqlmock`, which `go.mod` doesn't have — the real strategy is `t.TempDir()` + fixtures; +- it says HBD supports Chromium-based browsers and Firefox — Safari is missing, as in the root help text; +- it points at `crypto/abe_embed_windows.go` / `crypto/abe_stub_windows.go`, which now live in `crypto/windows/payload/`; +- its "`golang.org/x/text` will be removed" note is moot (the module is already indirect-only) and its "no `pkg/` + `internal/`" rule is superseded by [RFC-002](002-package-layout.md). + +In the code, the `pickTest` / `TestPickFromConfigs` names outlived the function they test (`discoverFromConfigs`) and go away with it. The README says `cookie-editor` skips non-cookie categories, while the code writes them as standard JSON; the contract freezes the code's behavior, so the README is corrected. The format and technique RFCs (013–021) keep today's type names until Phase 8 moves them to the new ones ([RFC-012](012-migration-roadmap.md)). No RFC citations go into source comments — traceability stays in git and these documents. + +## Coverage intent + +Coverage is a signal, not a target. The intent: every extractor has at least one golden fixture, every outcome has a planner test, every designed-out bug has a regression test, and every frozen surface has a compatibility test. Those guarantees matter more than a percentage. diff --git a/rfcs/012-migration-roadmap.md b/rfcs/012-migration-roadmap.md new file mode 100644 index 0000000..adaf457 --- /dev/null +++ b/rfcs/012-migration-roadmap.md @@ -0,0 +1,78 @@ +# RFC-012: Migration Roadmap + +## One integration branch + +The rewrite is built on the integration branch `refactor/main-v2`, cut from `main`, on the existing module path and with no v2. Every step is a pull request into that branch, squash-merged once CI is green, so each step becomes one commit whose title carries its PR number. `main` is frozen meanwhile — no Go changes and no bot commits land there — and keeps shipping v1.1.x from today's code. + +When Phase 8 is done, a final pull request from `refactor/main-v2` to `main` runs the full CI, and `main` is fast-forwarded to the branch, so every step commit keeps its order, its date, and its PR number. If `main` moved after all, the branch is first rebased onto it with `--committer-date-is-author-date`, building and testing every replayed commit. GitHub's "Rebase and merge" button is not used for that final step: it rewrites every commit's committer and date. + +Inside the branch the rewrite is still incremental: new `internal/` packages grow beside the current code, one base is wired end to end before the others follow, and old code is deleted only once its replacement is tested. Because the compatibility contract ([RFC-000](000-goals-and-constraints.md)) freezes the CLI and the output, "stable" is checkable: at no commit does a command line, an output file, a `keys.json`, or an archive change outside the listed fixes. Every commit builds and passes the compatibility suite, so `git bisect` works across the whole rewrite once it is on `main`. + +## Phase order + +Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layout.md)); then one vertical slice through the whole pipeline; then the rest of the browsers. A pure bottom-up order would first exercise the new stack end to end in its last phase, after weeks of adapters; the slice moves that moment to the middle. + +### Phase 0 — Scaffold and guardrails + +- Make `rfcs/` the one design record: the design RFCs (000–012) and the format and technique RFCs (013–021), indexed by `rfcs/README.md`; the RFCs they supersede are removed. +- Add `tagliatelle` ([RFC-011](011-testing-and-quality.md)), so every new record, `keys.json`, and manifest field keeps its snake_case wire name from day one. +- Pin CI to Go `1.20.x` and fail on any `go` directive other than `1.20` or on a `toolchain` line. +- Capture the compatibility goldens from today's code: the per-command CLI flag sets first; then output-parity fixtures for every format (with URLs that exercise JSON escaping), and sample `keys.json` files and archives. +- No behavior change. CLAUDE.md's "no `pkg/` + `internal/`" note is updated to reflect the `internal/`-only decision. + +### Phase 1 — Leaves + +- Move the utility code into named homes: `utils/sqliteutil` → `sqlitex`, the per-browser epoch helpers → `timeconv`, `log` → `internal/log` (name kept). +- These have no project-internal dependencies beyond `log`, so they move with mechanical refactors and their existing tests. + +### Phase 2 — `category`, `record`, and `export` + +- Introduce `internal/category` — `Category` with bare values numbered from 1, today's `String()` values, `All` and `Parse` — and `internal/record`: `Login`, `Cookie`, and the other record types with flat `Browser` + `Profile` fields followed by today's field names and order, set through `record.Stamp` ([RFC-003](003-core-types.md)). +- Apply the naming in [RFC-004](004-naming-decisions.md) verbatim: `types.Category` → `category.Category`, `types.LoginEntry` → `record.Login` and every other `…Entry` → its bare name, no `Category` prefix, no `Owner`/`Origin` umbrella. +- Move `output` to `internal/export` — `Writer` and the `csv`, `json`, and `cookie-editor` encoders — on the new record types ([RFC-008](008-output-and-export.md)). It depends only on `category`, `record`, and `log`. +- No output change: `tagliatelle` and the parity suite must stay green. + +### Phase 3 — `crypto`, `masterkey`, `keychain`, `winapi` + +- Make `crypto` pure primitives; move OS secret-store work into `masterkey` — retrievers per OS, `RetrieveAll` with first-key-wins per version and independent versions, `Version` as a string type, `DecryptDPAPI`, the `keys.json` `Dump` unchanged at version `"2"`, `ABEKind` ([RFC-006](006-key-retrieval-and-crypto.md)). No technique is rewritten — only the boundary is drawn. +- Add `internal/keychain` (macOS only): the login keychain handle, opened on first use and at most once per run. The macOS `v10` retriever reads through it from this phase, the Safari base when it is ported (Phase 6); today's separate password check and per-consumer keychain opens go away ([RFC-006](006-key-retrieval-and-crypto.md)). +- Fold `utils/{winapi,winutil}` into `internal/winapi`. The ABE unit — `utils/injector` and `crypto/windows/` with its C sources, generated `bootstrap` package, and `payload` embed package, plus `Makefile.frag` — stays where it is; only its importers change. Its move to `internal/abe/` is DEFERRED ([RFC-002](002-package-layout.md)). + +### Phase 4 — `snapshot` + +- Build `internal/snapshot` ([RFC-007](007-snapshot-and-acquisition.md)): `Dir` (`Temp`, `Open`, `Unzip`, `Capture`, `Snapshot`, `Zip`, `Close`) and `Snapshot.Path` with the per-file error contract, the copier with the Windows locked-file fallback and SQLite sidecars, user-data-dir IDs in the layout, `manifest.json`, and `0700` temp snapshot directories removed on every exit path. +- Replace `otiai10/copy` with the snapshot copier ([RFC-010](010-dependencies.md)). +- `archive` and `restore` move onto the snapshot; the archive-layout and `keys.json` compatibility tests guard both directions. + +### Phase 5 — Vertical slice: the Chromium base end to end + +- Add the `browser.Def` table with the Chromium rows, `browser.ProfileSnapshot` and the per-dir `MasterKeys` call-once in `app` (with the run's login keychain added to the `Locator` on macOS), the Chromium base package (`Discover`, `Extractors`, `KeyLocator`, `ArchiveSources`, the Yandex and Opera overrides), and the `app` stages — `Validate`, `Discover`, `NewPlan`, `Execute`, `Report` ([RFC-001](001-architecture-and-pipeline.md)). +- The new path runs beside today's; on the fixtures its output must equal the Phase 0 goldens byte for byte, and the Windows host compares it against the cookie/key baseline. + +### Phase 6 — Widen: Firefox and Safari + +- Port the Firefox and Safari bases one category at a time, each with a `testdata/` fixture and golden. +- Land the listed output fixes here — Firefox history order and bookmark fields, Safari bookmark IDs — each with its regression test and as an expected diff in the parity suite. + +### Phase 7 — Switch over + +- `dump`, `dumpkeys`, `archive`, `restore`, and `list` run on the pipeline. +- Validate-first ordering, `--keychain-pw-stdin` with the new precedence, the `-p` fixes, the safe `--zip` order, and the `restore` stamp fix ([RFC-009](009-cli-surface.md)). + +### Phase 8 — Delete & document + +- Remove the superseded top-level packages — `browser/`, `crypto/` except the ABE unit's `crypto/windows/`, `filemanager/`, `log/`, `masterkey/`, `output/`, `types/`, and `utils/` except `utils/injector` — once nothing references them. +- Update CLAUDE.md (the new paths), the README (Safari, the `cookie-editor` behavior), and the root help text. +- Bring the RFCs to their finished state: the format and technique RFCs (013–021) move from today's type names — `BrowserConfig`, `WindowsABE`, `winutil.Table`, `Hints`, the `Retrievers` struct — to the names in [RFC-004](004-naming-decisions.md); the design RFCs describe the code as it is instead of comparing it with today's; and this roadmap is removed. +- Final `go mod tidy` under go@1.20; confirm the `go` directive is still `1.20` and `otiai10/copy` and `mint` are gone. + +## Guardrails per phase + +- Every phase keeps `go build ./cmd/hack-browser-data/` green on Go 1.20.x across all three OSes. +- Every phase keeps the compatibility suite green: the same flag sets, byte-identical output except for the listed fixes, and readable `keys.json` and archives in both directions. +- Every phase is one or more reviewable PRs into `refactor/main-v2`, each with its own tests; no PR depends on a later one to compile. +- The Windows ABE and locked-file smoke test runs at the end of Phases 3, 4, 5, and 7 — the phases that can affect key retrieval or acquisition — against the current cookie/key baseline, on the dedicated Windows host. + +## What ships when + +Nothing from the rewrite ships before it reaches `main`. Until then `main` keeps releasing v1.1.x from today's code; after the fast-forward, the next release is cut from the rewritten tree. Because the CLI and the output are frozen, users see no difference except the listed fixes. diff --git a/rfcs/002-chromium-data-storage.md b/rfcs/013-chromium-data-storage.md similarity index 78% rename from rfcs/002-chromium-data-storage.md rename to rfcs/013-chromium-data-storage.md index b463be0..a2996ee 100644 --- a/rfcs/002-chromium-data-storage.md +++ b/rfcs/013-chromium-data-storage.md @@ -1,24 +1,24 @@ -# RFC-002: Chromium Data Storage +# RFC-013: Chromium Data Storage -**Author**: moonD4rk -**Status**: Living Document +**Author**: moonD4rk\ +**Status**: Living Document\ **Created**: 2026-04-05 ## 1. Data File Locations All paths are relative to the profile directory (e.g. `~/.config/google-chrome/Default/`). -| Category | Candidate Paths (priority order) | Format | -|----------|----------------------------------|--------| -| Password | `Login Data` | SQLite | -| Cookie | `Network/Cookies`, `Cookies` | SQLite | -| History | `History` | SQLite | -| Download | `History` (same file) | SQLite | -| Bookmark | `Bookmarks` | JSON | -| CreditCard | `Web Data` | SQLite | -| Extension | `Secure Preferences` | JSON | -| LocalStorage | `Local Storage/leveldb/` | LevelDB dir | -| SessionStorage | `Session Storage/` | LevelDB dir | +| Category | Candidate Paths (priority order) | Format | +| -------------- | -------------------------------- | ----------- | +| Password | `Login Data` | SQLite | +| Cookie | `Network/Cookies`, `Cookies` | SQLite | +| History | `History` | SQLite | +| Download | `History` (same file) | SQLite | +| Bookmark | `Bookmarks` | JSON | +| CreditCard | `Web Data` | SQLite | +| Extension | `Secure Preferences` | JSON | +| LocalStorage | `Local Storage/leveldb/` | LevelDB dir | +| SessionStorage | `Session Storage/` | LevelDB dir | Cookies have two candidate paths because older Chromium versions stored cookies at `/Cookies`, while newer versions moved them to `/Network/Cookies`. The first existing path wins. @@ -28,14 +28,14 @@ Cookies have two candidate paths because older Chromium versions stored cookies Yandex overrides two file names from the standard Chromium layout: -| Category | Standard Chromium | Yandex | -|----------|-------------------|--------| -| Password | `Login Data` | `Ya Passman Data` | -| CreditCard | `Web Data` | `Ya Credit Cards` | +| Category | Standard Chromium | Yandex | +| ---------- | ----------------- | ----------------- | +| Password | `Login Data` | `Ya Passman Data` | +| CreditCard | `Web Data` | `Ya Credit Cards` | Yandex's password query selects extra columns (`username_element`, `password_element`, `signon_realm`) beyond the standard four; these columns are used to construct the per-row AAD for decryption. The URL column is `origin_url`, same as standard Chromium. -Yandex passwords and credit cards use Yandex's proprietary two-layer encryption (see RFC-012) and are fully supported. Cookie decryption follows standard Chromium v10/v20 paths. +Yandex passwords and credit cards use Yandex's proprietary two-layer encryption (see RFC-017) and are fully supported. Cookie decryption follows standard Chromium v10/v20 paths. ### 2.2 Opera @@ -63,7 +63,7 @@ Certain directories are always skipped: `System Profile`, `Guest Profile`, and ` SELECT origin_url, username_value, password_value, date_created FROM logins ``` -The `password_value` column contains encrypted bytes. See [RFC-003](003-chromium-encryption.md) for decryption. +The `password_value` column contains encrypted bytes. See [RFC-014](014-chromium-encryption.md) for decryption. ### 4.2 Cookies (Cookies -- SQLite) @@ -132,8 +132,8 @@ Chromium uses WebKit epoch timestamps: microseconds since 1601-01-01 00:00:00 UT ## Related RFCs -| RFC | Topic | -|-----|-------| -| [RFC-003](003-chromium-encryption.md) | Chromium encryption mechanisms per platform | -| [RFC-006](006-key-retrieval-mechanisms.md) | Platform-specific master key retrieval | -| [RFC-008](008-file-acquisition-and-platform-quirks.md) | File acquisition and platform quirks | +| RFC | Topic | +| ------------------------------------------ | ------------------------------------------- | +| [RFC-014](014-chromium-encryption.md) | Chromium encryption mechanisms per platform | +| [RFC-015](015-key-retrieval-mechanisms.md) | Platform-specific master key retrieval | +| [RFC-007](007-snapshot-and-acquisition.md) | Snapshot-first file acquisition | diff --git a/rfcs/013-cli-redesign-cross-host.md b/rfcs/013-cli-redesign-cross-host.md deleted file mode 100644 index 747323d..0000000 --- a/rfcs/013-cli-redesign-cross-host.md +++ /dev/null @@ -1,129 +0,0 @@ -# RFC-013: CLI Redesign — Flat-Verb Surface & Cross-Host Restore - -**Author**: moonD4rk -**Status**: Implemented — `archive` (#610); cross-platform `restore` (#611) -**Created**: 2026-06-03 -**Revised**: 2026-06-06 (subdir-convention archive, dual-mode restore, Local State, delivery order) - -## 1. Summary - -The command-line surface has accreted two grammars: flat task-verbs (`dump`, `list`) alongside a noun-grouped `keys export` / `keys import` family. This RFC redesigns the whole surface around one grammar — flat verbs — and specifies the cross-host workflow end to end: export master keys on the origin host, archive the minimal data files, and restore (decrypt) them offline on an analyst host of any platform. It also records the structural problem the redesign exists to solve: the set of browsers a command can act on is platform-specific, yet cross-host restore must work for browsers that were never built for the analyst's OS. Breaking changes are accepted (pre-1.0); the method is CLI-first, deriving the internal data model backwards from the chosen surface. - -## 2. Motivation - -### 2.1 Two grammars in one tool - -`dump` and `list` are flat task-verbs — the verb *is* the action. `keys export` / `keys import` is a noun-then-action grammar that implies a `keys` resource with sub-operations. Mixing the two in one small CLI reads as inconsistent: there is no `data export` or `browser list` to make the noun grammar systematic, so `keys` stands alone as a special case. The aim is a tool like kubectl — predictable because it is uniformly `verb resource` — but without kubectl's complexity. For a tool this size, the matching "simple and consistent" choice is uniformly flat verbs. - -### 2.2 The cross-host workflow is half-automated - -Cross-host decryption (export keys on the origin, decrypt a copied profile on the analyst host) shipped in #599–#605, but only the *keys* half is automated. The analyst still copies the origin's profile data by hand — awkward because the live SQLite files are locked on Windows, the full `User Data` tree is huge (caches), and only a handful of small files actually matter for decryption (#607). - -### 2.3 Restore is bound to the local platform browser table (#606) - -The consumer side reuses `DiscoverBrowsers`, which iterates `platformBrowsers()` — the browser table for the *analyst's* OS, selected by build tag (`browser_{darwin,windows,linux}.go`). A Windows-only fork such as Sogou / QQ / 360 lives only in the Windows table. On macOS, `restore -b sogou` matches nothing and aborts with `no browsers found`, even with a valid `keys.json` and the data supplied explicitly. This is the crux: the browsers a command may act on are platform-specific, but cross-host restore must transcend that — given a key and the data, it should decrypt any Chromium profile regardless of whether that browser exists on the analyst platform. - -## 3. Proposed CLI surface - -Six flat verbs, one grammar: - -``` -hack-browser-data [flags] # default → dump (also Windows double-click) - dump -b -c -f -d -p --zip # local: decrypt this host's browsers → data - dumpkeys -b -o [--keychain-pw] # origin: master keys → keys.json (stdout default) - archive -b -c -o # origin: minimal decryption-relevant files → zip - restore --keys K (--data-dir D | --data-zip Z) [-b] -c -f -d # analyst: keys.json + data → decrypted - list [--detail] - version -``` - -Workflows: - -``` -local : hbd dump -b chrome -c cookie,password -cross-host: origin> hbd dumpkeys -o keys.json - origin> hbd archive -b chrome -o browser-data.zip - analyst> hbd restore --keys keys.json --data-zip browser-data.zip -c cookie -``` - -The `keys` parent command is removed: `keys export` becomes `dumpkeys`, `keys import` becomes `restore`, and a new `archive` fills the missing data-transport step. `dump` / `list` / `version` keep their current behavior; `dump` stays the default when no subcommand is given (which also covers the Windows double-click case). - -## 4. The browser-universe model - -The resolution to §2.3 is a single rule: **the set of browsers a command may act on — its "universe" — matches the nature of that command.** - -| Command | Browser universe | `-b sogou` on macOS | -|---------|------------------|---------------------| -| `dump` / `dumpkeys` / `archive` / `list` | the local `platformBrowsers()` table (what this OS installs) | correctly fails — Sogou is not on macOS | -| `restore` | the `keys.json` itself (whatever the origin exported) | succeeds — the dump contains a Sogou vault | - -`dump`, `dumpkeys`, `archive`, and `list` act on browsers *installed on this host*, so the platform table is the right source and `-b`'s vocabulary is the local set. `restore` acts on *transported artifacts that may have come from any platform*, so its universe is the `keys.json`, and `-b` validates against the dump's vaults, not the local table. Stated plainly: **the browsers you can restore are exactly the browsers in your `keys.json`.** This turns the platform difference from a bug into a property, and it is what makes #606 dissolve rather than be patched. - -## 5. Cross-host artifacts and the restore command - -The cross-host producer emits two independent, composable artifacts; the consumer takes both. - -- `dumpkeys` writes `keys.json` — the portable master keys (stdout by default for `ssh origin hbd dumpkeys | …` pipelines; `-o` for a 0600 file). -- `archive` writes `browser-data.zip` — the decryption-relevant files for the requested `-c` categories (`Login Data`, `Cookies`, `Web Data`, `History`, …), read through the existing locked-file bypass. To carry more than one browser and to keep restore unambiguous, the zip is laid out as `/` (e.g. `chrome/Default/Network/Cookies`) — one subdir per installation, each subdir being that browser's `User Data` root. Two things are always included regardless of `-c`: each profile's `Preferences`/`Preferences_02` (so restore can rediscover the profile — the marker is no extraction source) and the installation's `Local State` (carried for fidelity only; restore decrypts with the keys in `keys.json` and never reads it). Zip entry names are always forward-slash, so a Windows-produced archive restores on macOS/Linux. -- `restore` takes `--keys keys.json` and the data via two explicit flags, `--data-dir ` or `--data-zip ` (mutually exclusive, exactly one required). A zip is extracted to a temporary directory; a directory is used as-is, so `unzip browser-data.zip -d X && restore --data-dir X` equals `restore --data-zip browser-data.zip`. The data resolves two ways: when it holds `/` subdirs (the `archive` layout) each vault is rooted at its own subdir and several browsers restore at once; otherwise `--data-dir` is a single browser's hand-copied `User Data` root, which is unambiguous only for one vault — so `-b` must select it. This preserves the pre-redesign "point at a copied profile folder" workflow. - -`restore` is a **separate verb**, not a `dump --keys` mode. Folding it into `dump` would force one command to carry two mutually-exclusive input modes (`-b` for local discovery xor `--keys/--data` for transported artifacts) and dead flags (a `--keychain-pw` that silently does nothing once keys are supplied — a friction the earlier `dump --keys` design already hit). One verb, one job keeps each command's flags and help self-contained. `restore -b` is an **optional filter** over the dump's vaults, not a required selector, because the dump self-describes what each vault is (§4, §6). - -## 6. The cross-platform identity problem (#606): implementation options - -Grounding facts: - -- Every browser in the tables resolves to one of three engine kinds. All Windows-only forks (`360`, `360x`, `qq`, `sogou`, `dc`, `arc`, …) are `types.Chromium`; only Opera is `ChromiumOpera` and Yandex is `ChromiumYandex`. **Three kinds cover every fork.** -- The extraction logic (`sourcesForKind` / `extractorsForKind`) carries no build tags — it is OS-independent. A Sogou profile decrypts through the generic Chromium path with no Sogou-specific code. -- So restore needs only the **engine kind** (one of three) plus the data path and the keys. Everything else in `BrowserConfig` (display name, keychain label, ABE flag, default install path) is either a label or is used solely for *local* key derivation and discovery — all irrelevant once static keys and an explicit data path are supplied. - -Two ways to give restore the kind for a browser absent from the analyst's table: - -**Option A — self-describing dump (chosen).** The `keys.json` vault carries the kind. `restore` reads it and constructs a generic engine of that kind rooted at the supplied data path; it never consults `platformBrowsers()`. Minimal, and maximally robust: even a fork this build has never heard of by name still restores as long as its kind is one of the three. - -**Option B — global, OS-independent browser registry.** Split the three per-OS tables into one full-fork registry (carrying kind) plus per-OS views that add paths and ABE flags. `-b`, help text, and `list` would then recognize every fork on any OS. This is a larger refactor and is not required for restore (restore always has a `keys.json` to serve as its universe); it is worth doing only if cross-platform `-b` / `list` awareness is a goal in its own right. - -**Decision: Option A.** The `keys.json` vault carries the engine kind, and `restore` constructs from it without ever consulting `platformBrowsers()`. Option B above is the considered, rejected alternative. - -This crystallizes the principle that lets cross-platform decryption and the current local mode coexist: **one engine constructor (`chromium.NewBrowser`), two config sources.** Local commands feed it configs from the per-OS `platformBrowsers()` table — unchanged; `restore` feeds it configs synthesized from the keys.json vaults. The cross-platform capability is an additive second source confined to the restore path, so the local mode is left untouched. - -## 7. Downstream architecture implications (derived from the surface) - -Working backwards from the chosen surface: - -- **keydump struct** (`masterkey/dump.go`): the vault carries the engine kind so restore can construct without the local table. The `Browser` field becomes the canonical key (it was the display name), a `Kind` string field is added (values `chromium` / `chromium-yandex` / `chromium-opera`, mapped to/from the internal enum by an explicit bijection so a reordered enum can't silently corrupt), and `DumpVersion` is bumped to "2". The format is designed fresh — `ReadJSON` rejects other versions and there are no backward-compat shims for pre-redesign dumps. `UserDataDir` and `Profiles` remain informational. The keys stay `V10` / `V11` / `V20` (Chromium-only; Firefox keys are out of scope, §9). -- **`browser/keydump.go`**: `BuildDump` records the key and kind; the overlay `ApplyDump` (which mutates locally-discovered browsers) is replaced by `BuildFromDump`, which synthesizes a `BrowserConfig` per vault and builds the engine directly — no `platformBrowsers()` dependency. It resolves the data via the subdir convention or, for a hand-copied folder, the supplied dir as a single browser's root (§5). This is the mechanical form of §4. -- **`archive`** reuses the engine's per-category source resolution through a new `ArchiveSources` accessor — each source path is kept slash-canonical so the forward-slash zip entry name falls out directly — plus the existing locked-file session. The flattening `CompressDir` helper is unfit (it drops the layout and deletes the source), so `archive` uses a new layout-preserving `ZipDir`, and `restore --data-zip` a Zip-Slip-safe `Unzip`. -- **cmd layer**: drop the `keys` parent; add `dumpkeys`, `archive`, `restore` as siblings of `dump` / `list` / `version`. -- **Cross-cutting (orthogonal to the taxonomy)**: a Chromium-import password CSV format (`name,url,username,password,note`, #602) and category-aware credential prompting so a no-decryption request never asks for a password (#570). - -## 8. Decisions (2026-06-03) - -1. The browser-universe model (§4) is adopted: `restore`'s `-b` validates against the dump, not the local table. -2. #606 implementation: **Option A** — self-describing dump (§6). -3. keydump vault identity: **option 1A** — `Browser` becomes the canonical key and a `Kind` field is added (§7). -4. Verb names are final: `archive` and `restore`. - -### Refinements (2026-06-06) - -5. Archive layout is the subdir convention `/` (multi-browser); `restore` is dual-mode — that layout, or a single hand-copied `User Data` root selected by `-b` (§5). -6. `archive` always includes each profile's `Preferences` marker (required for restore's profile discovery) and the installation's `Local State` (fidelity only — restore decrypts from `keys.json` and never reads it; §5). -7. No backward compatibility: the dump format is designed fresh, with no shims for pre-redesign artifacts. -8. Delivery order: `archive` (#607) lands first as an independent PR (it stands alone — its output also feeds the current overlay `restore` for same-OS browsers); the self-describing cross-platform `restore` (#606) follows. - -## 9. Non-goals / deferred - -- Firefox / Safari key export (Firefox keys are per-profile NSS; Safari has no portable key). -- A single self-describing bundle fusing keys + data into one file (the composable two-artifact model is chosen for now). -- Encrypted or signed dump artifacts. -- The global browser registry (§6 Option B), unless adopted for #606. - -## Related RFCs - -| RFC | Topic | -|-----|-------| -| [RFC-007](007-cli-and-output-design.md) | The CLI and output design this RFC revises | -| [RFC-003](003-chromium-encryption.md) | Cipher version dispatch (v10/v11/v20) consumed by restore | -| [RFC-006](006-key-retrieval-mechanisms.md) | Master-key retrieval the cross-host split externalizes | -| [RFC-001](001-project-architecture.md) | Browser interface and Extract() orchestration | -| [RFC-008](008-file-acquisition-and-platform-quirks.md) | Locked-file session and ZipDir used by archive | diff --git a/rfcs/003-chromium-encryption.md b/rfcs/014-chromium-encryption.md similarity index 73% rename from rfcs/003-chromium-encryption.md rename to rfcs/014-chromium-encryption.md index 0f477b2..0457466 100644 --- a/rfcs/003-chromium-encryption.md +++ b/rfcs/014-chromium-encryption.md @@ -1,7 +1,7 @@ -# RFC-003: Chromium Encryption +# RFC-014: Chromium Encryption -**Author**: moonD4rk -**Status**: Living Document +**Author**: moonD4rk\ +**Status**: Living Document\ **Created**: 2026-04-05 ## 1. Overview @@ -14,13 +14,13 @@ Non-sensitive categories (history, bookmarks, downloads, extensions, storage) ar Every encrypted value begins with a 3-byte prefix that identifies the cipher version: -| Prefix | Version | Meaning | -|--------|---------|---------| -| `v10` | CipherV10 | Chrome 80+ standard encryption (AES-GCM on Windows, AES-CBC on macOS/Linux) | -| `v11` | CipherV11 | Linux-only: AES-CBC variant where the key comes from libsecret / kwallet. Same algorithm and parameters as `v10` — only the key source differs | -| `v12` | CipherV12 | Chromium SecretPortal/Flatpak (xdg-desktop-portal) — recognized by the version detector so a clear error can be returned; not yet implemented | -| `v20` | CipherV20 | Chrome 127+ App-Bound Encryption | -| (none) | CipherDPAPI | Pre-Chrome 80 raw DPAPI encryption (Windows only, no prefix) | +| Prefix | Version | Meaning | +| ------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `v10` | CipherV10 | Chrome 80+ standard encryption (AES-GCM on Windows, AES-CBC on macOS/Linux) | +| `v11` | CipherV11 | Linux-only: AES-CBC variant where the key comes from libsecret / kwallet. Same algorithm and parameters as `v10` — only the key source differs | +| `v12` | CipherV12 | Chromium SecretPortal/Flatpak (xdg-desktop-portal) — recognized by the version detector so a clear error can be returned; not yet implemented | +| `v20` | CipherV20 | Chrome 127+ App-Bound Encryption | +| (none) | CipherDPAPI | Pre-Chrome 80 raw DPAPI encryption (Windows only, no prefix) | If the ciphertext is shorter than 3 bytes or the prefix is unrecognized, it is treated as legacy DPAPI. @@ -28,11 +28,11 @@ If the ciphertext is shorter than 3 bytes or the prefix is unrecognized, it is t Chromium on macOS stores a per-browser secret in the macOS Keychain (e.g. "Chrome Safe Storage", "Brave Safe Storage"). The master key is derived from this secret via PBKDF2: -| Parameter | Value | -|-----------|-------| -| Hash | SHA-1 | -| Salt | `saltysalt` | -| Iterations | 1003 | +| Parameter | Value | +| ---------- | ------------------ | +| Hash | SHA-1 | +| Salt | `saltysalt` | +| Iterations | 1003 | | Key length | 16 bytes (AES-128) | Decryption uses AES-128-CBC with a fixed IV of 16 space bytes (`0x20`). The ciphertext layout: @@ -43,7 +43,7 @@ Decryption uses AES-128-CBC with a fixed IV of 16 space bytes (`0x20`). The ciph | 3B | remaining bytes | ``` -There are three retrieval strategies, tried in order: (1) gcoredump exploit for securityd process memory, (2) direct keychain unlock with user's login password, (3) `security` CLI command (may trigger a GUI prompt). See [RFC-006](006-key-retrieval-mechanisms.md) for details. +There are three retrieval strategies, tried in order: (1) gcoredump exploit for securityd process memory, (2) direct keychain unlock with user's login password, (3) `security` CLI command (may trigger a GUI prompt). See [RFC-015](015-key-retrieval-mechanisms.md) for details. ## 4. Windows Encryption @@ -78,11 +78,11 @@ Chromium on Linux has two obfuscation prefixes that share the same AES-128-CBC a Both prefixes are derived through the same PBKDF2 parameters: -| Parameter | Value | -|-----------|-------| -| Hash | SHA-1 | -| Salt | `saltysalt` | -| Iterations | 1 | +| Parameter | Value | +| ---------- | ------------------ | +| Hash | SHA-1 | +| Salt | `saltysalt` | +| Iterations | 1 | | Key length | 16 bytes (AES-128) | Decryption uses AES-128-CBC with a fixed IV of 16 space bytes (`0x20`) and PKCS5 padding — identical to macOS except for the PBKDF2 iteration count. @@ -119,7 +119,7 @@ Each record is decrypted independently. A failure to decrypt one value does not ## Related RFCs -| RFC | Topic | -|-----|-------| -| [RFC-002](002-chromium-data-storage.md) | Chromium data file locations and storage formats | -| [RFC-006](006-key-retrieval-mechanisms.md) | Platform-specific master key retrieval | +| RFC | Topic | +| ------------------------------------------ | ------------------------------------------------ | +| [RFC-013](013-chromium-data-storage.md) | Chromium data file locations and storage formats | +| [RFC-015](015-key-retrieval-mechanisms.md) | Platform-specific master key retrieval | diff --git a/rfcs/006-key-retrieval-mechanisms.md b/rfcs/015-key-retrieval-mechanisms.md similarity index 67% rename from rfcs/006-key-retrieval-mechanisms.md rename to rfcs/015-key-retrieval-mechanisms.md index 52f0ec9..4daf165 100644 --- a/rfcs/006-key-retrieval-mechanisms.md +++ b/rfcs/015-key-retrieval-mechanisms.md @@ -1,22 +1,22 @@ -# RFC-006: Key Retrieval Mechanisms +# RFC-015: Key Retrieval Mechanisms -**Author**: moonD4rk -**Status**: Living Document +**Author**: moonD4rk\ +**Status**: Living Document\ **Created**: 2026-04-05 ## 1. Overview Chromium-based browsers encrypt sensitive data (passwords, cookies, credit cards) using a **master key**. The master key is stored differently on each platform: -| Platform | Storage | Key Type | -|----------|---------|----------| -| macOS | macOS Keychain | Password string → PBKDF2 → AES-128 | -| Windows | `Local State` JSON (DPAPI-encrypted) | Raw AES-256 key | -| Linux | GNOME Keyring / KDE Wallet via D-Bus | Password string → PBKDF2 → AES-128 | +| Platform | Storage | Key Type | +| -------- | ------------------------------------ | ---------------------------------- | +| macOS | macOS Keychain | Password string → PBKDF2 → AES-128 | +| Windows | `Local State` JSON (DPAPI-encrypted) | Raw AES-256 key | +| Linux | GNOME Keyring / KDE Wallet via D-Bus | Password string → PBKDF2 → AES-128 | Each platform may have multiple retrieval strategies. The `Retriever` interface and `ChainRetriever` pattern abstract over these strategies, trying each in priority order until one succeeds. -For Chromium encryption details (cipher versions, AES-CBC/GCM), see [RFC-003](003-chromium-encryption.md). Firefox manages its own keys via `key4.db` — see [RFC-005](005-firefox-encryption.md). +For Chromium encryption details (cipher versions, AES-CBC/GCM), see [RFC-014](014-chromium-encryption.md). Firefox manages its own keys via `key4.db` — see [RFC-019](019-firefox-encryption.md). ## 2. Retriever Interface @@ -57,22 +57,22 @@ Chromium on macOS stores the encryption password in the user's login keychain un ### 3.2 Chain Order -| Priority | Strategy | Requires | Interactive? | -|----------|----------|----------|:------------:| -| 1 | Gcoredump (CVE-2025-24204) | Root | No | -| 2 | Keychain password | `--keychain-pw` flag | No | -| 3 | `security` CLI command | Nothing | Yes (dialog) | +| Priority | Strategy | Requires | Interactive? | +| -------- | -------------------------- | -------------------- | :----------: | +| 1 | Gcoredump (CVE-2025-24204) | Root | No | +| 2 | Keychain password | `--keychain-pw` flag | No | +| 3 | `security` CLI command | Nothing | Yes (dialog) | ### 3.3 PBKDF2 Derivation All macOS strategies produce a raw password string from the keychain. This is derived into an AES-128 key via PBKDF2: -| Parameter | Value | Source | -|-----------|-------|--------| -| Salt | `"saltysalt"` | [os_crypt_mac.mm](https://source.chromium.org/chromium/chromium/src/+/master:components/os_crypt/os_crypt_mac.mm;l=157) | -| Iterations | 1003 | | -| Key length | 16 bytes (AES-128) | | -| Hash | HMAC-SHA1 | | +| Parameter | Value | Source | +| ---------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------- | +| Salt | `"saltysalt"` | [os_crypt_mac.mm](https://source.chromium.org/chromium/chromium/src/+/master:components/os_crypt/os_crypt_mac.mm;l=157) | +| Iterations | 1003 | | +| Key length | 16 bytes (AES-128) | | +| Hash | HMAC-SHA1 | | ### 3.4 Keychain Labels @@ -82,13 +82,14 @@ The authoritative mapping lives in the `KeychainLabel` field of each entry in `p ## 4. Windows Key Retrieval -Chromium on Windows stores **two** master keys in `Local State` JSON: a legacy v10 key (`os_crypt.encrypted_key`, DPAPI-wrapped) and, since Chrome 127, an App-Bound Encryption v20 key (`os_crypt.app_bound_encrypted_key`, IElevator-wrapped). Both tiers can coexist on a single profile — Chrome 127+ encrypts *new* cookies with v20 but leaves pre-existing passwords and old cookies on v10 — so the retriever layer fetches both keys independently rather than via a ChainRetriever (see §4.4 and issue #578). +Chromium on Windows stores **two** master keys in `Local State` JSON: a legacy v10 key (`os_crypt.encrypted_key`, DPAPI-wrapped) and, since Chrome 127, an App-Bound Encryption v20 key (`os_crypt.app_bound_encrypted_key`, IElevator-wrapped). Both tiers can coexist on a single profile — Chrome 127+ encrypts _new_ cookies with v20 but leaves pre-existing passwords and old cookies on v10 — so the retriever layer fetches both keys independently rather than via a ChainRetriever (see §4.4 and issue #578). ### 4.1 DPAPI Background Windows Data Protection API (DPAPI) is a built-in symmetric encryption service provided by `Crypt32.dll`. It uses the logged-in user's Windows credentials (derived from the user's login password) as the root key material. Applications call `CryptProtectData` to encrypt and `CryptUnprotectData` to decrypt, without needing to manage keys themselves. Key characteristics: + - **User-scoped** — data encrypted by one Windows user cannot be decrypted by another user, even on the same machine - **Machine-bound** — the encrypted blob cannot be decrypted on a different machine (unless roaming credentials are used) - **No password prompt** — decryption is transparent to the calling process as long as it runs under the correct user session @@ -111,16 +112,16 @@ The implementation loads `Crypt32.dll` at runtime via `syscall.NewLazyDLL` and c ### 4.3 No PBKDF2 Needed -Unlike macOS/Linux, DPAPI gives the **final AES-256 key directly**. No intermediate password, no derivation step. The key is used as-is for AES-256-GCM decryption (see [RFC-003](003-chromium-encryption.md)). +Unlike macOS/Linux, DPAPI gives the **final AES-256 key directly**. No intermediate password, no derivation step. The key is used as-is for AES-256-GCM decryption (see [RFC-014](014-chromium-encryption.md)). ### 4.4 Dual-Tier Retrievers (V10 + V20) Windows populates two slots of the `masterkey.Retrievers` struct — V10 (legacy DPAPI) and V20 (Chrome 127+ App-Bound Encryption) — which run independently rather than as a first-success chain. V11 stays nil on Windows (Chromium does not emit v11 prefix there). -| Slot | Retriever | Source field | Mechanism | -|------|-----------|--------------|-----------| -| V10 | `DPAPIRetriever` | `os_crypt.encrypted_key` | `CryptUnprotectData` (Crypt32.dll) | -| V20 | `ABERetriever` | `os_crypt.app_bound_encrypted_key` | IElevator via reflective injection (see [RFC-010](010-chrome-abe-integration.md)) | +| Slot | Retriever | Source field | Mechanism | +| ---- | ---------------- | ---------------------------------- | --------------------------------------------------------------------------------- | +| V10 | `DPAPIRetriever` | `os_crypt.encrypted_key` | `CryptUnprotectData` (Crypt32.dll) | +| V20 | `ABERetriever` | `os_crypt.app_bound_encrypted_key` | IElevator via reflective injection (see [RFC-016](016-chrome-abe-integration.md)) | `browser/browser_windows.go::newCredentialInjector` calls `masterkey.DefaultRetrievers()` and wires the resulting struct through `Browser.SetRetrievers(r)`. At extract time `masterkey.NewMasterKeys` runs each slot independently — a failure on one tier does not prevent the other from succeeding, because mixed-tier Chrome profiles (upgraded from pre-127) need partial success to be useful. @@ -134,10 +135,10 @@ Windows populates two slots of the `masterkey.Retrievers` struct — V10 (legacy Linux populates two slots of the `masterkey.Retrievers` struct — one per cipher prefix that Chromium emits on this platform: -| Slot | Prefix | Retriever | Mechanism | Chromium name | -|------|--------|-----------|-----------|---------------| -| V10 | `v10` | `PosixRetriever` | PBKDF2(`"peanuts"`) | kV10Key (matches upstream `PosixKeyProvider`) | -| V11 | `v11` | `DBusRetriever` | PBKDF2(D-Bus Secret Service password) | kV11Key (matches upstream `FreedesktopSecretKeyProvider`) | +| Slot | Prefix | Retriever | Mechanism | Chromium name | +| ---- | ------ | ---------------- | ------------------------------------- | --------------------------------------------------------- | +| V10 | `v10` | `PosixRetriever` | PBKDF2(`"peanuts"`) | kV10Key (matches upstream `PosixKeyProvider`) | +| V11 | `v11` | `DBusRetriever` | PBKDF2(D-Bus Secret Service password) | kV11Key (matches upstream `FreedesktopSecretKeyProvider`) | V20 stays nil on Linux (App-Bound Encryption is Windows-only). v12 (Chromium's `SecretPortalKeyProvider`, Flatpak/xdg-desktop-portal) is a separate tier not yet implemented — see the `CipherV12` case in `decryptValue`. @@ -155,12 +156,12 @@ The split mirrors the Windows V10/V20 fix (§4.4) and the root-cause logic of is Both strategies produce a password, derived via PBKDF2 with notably weaker parameters than macOS: -| Parameter | Value | Source | -|-----------|-------|--------| -| Salt | `"saltysalt"` | [os_crypt_linux.cc](https://source.chromium.org/chromium/chromium/src/+/main:components/os_crypt/os_crypt_linux.cc;l=100) | -| Iterations | **1** | | -| Key length | 16 bytes (AES-128) | | -| Hash | HMAC-SHA1 | | +| Parameter | Value | Source | +| ---------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- | +| Salt | `"saltysalt"` | [os_crypt_linux.cc](https://source.chromium.org/chromium/chromium/src/+/main:components/os_crypt/os_crypt_linux.cc;l=100) | +| Iterations | **1** | | +| Key length | 16 bytes (AES-128) | | +| Hash | HMAC-SHA1 | | A single iteration makes PBKDF2 essentially a keyed HMAC — no real key-stretching. Combined with the well-known fallback password `"peanuts"`, Linux Chromium encryption is trivial to break without the keyring. @@ -172,11 +173,11 @@ The authoritative mapping lives in the `KeychainLabel` field of each entry in `p ## 6. Platform Summary -| Platform | Retrievers (slots populated) | PBKDF2 | Key Size | -|----------|------------------------------|:------:|----------| -| macOS | V10 = chain(Gcoredump → KeychainPassword* → SecurityCmd) | 1003 iterations | AES-128 | -| Windows | V10 = DPAPIRetriever; V20 = ABERetriever (Chrome 127+) | No | AES-256 | -| Linux | V10 = PosixRetriever ("peanuts" kV10Key); V11 = DBusRetriever (keyring kV11Key) | 1 iteration | AES-128 | +| Platform | Retrievers (slots populated) | PBKDF2 | Key Size | +| -------- | ------------------------------------------------------------------------------- | :-------------: | -------- | +| macOS | V10 = chain(Gcoredump → KeychainPassword* → SecurityCmd) | 1003 iterations | AES-128 | +| Windows | V10 = DPAPIRetriever; V20 = ABERetriever (Chrome 127+) | No | AES-256 | +| Linux | V10 = PosixRetriever ("peanuts" kV10Key); V11 = DBusRetriever (keyring kV11Key) | 1 iteration | AES-128 | \* Only included when a non-empty password resolves — either via `--keychain-pw` flag or an interactive TTY prompt. @@ -188,17 +189,17 @@ This is a deliberate architectural choice, not an oversight. The following secti ### 7.1 Why Safari Does Not Share the Chromium Chain -| Aspect | Chromium chain | Safari direct access | -|---|---|---| -| Output | A 16-byte AES-128 key | A list of `InternetPassword` records | -| Use case | Decrypt Login Data DB | Records *are* the credentials | -| Number of consumers | 10+ Chromium variants | 1 (Safari only) | -| Failure mode | Hard fail (no key → cannot decrypt) | Soft fail (degrade to metadata-only) | -| Caching benefit | High (multi-profile, multi-browser) | None (single browser, single call) | +| Aspect | Chromium chain | Safari direct access | +| ------------------- | ----------------------------------- | ------------------------------------ | +| Output | A 16-byte AES-128 key | A list of `InternetPassword` records | +| Use case | Decrypt Login Data DB | Records _are_ the credentials | +| Number of consumers | 10+ Chromium variants | 1 (Safari only) | +| Failure mode | Hard fail (no key → cannot decrypt) | Soft fail (degrade to metadata-only) | +| Caching benefit | High (multi-profile, multi-browser) | None (single browser, single call) | -Forcing Safari through the `Retriever` interface would require returning a different type than `[]byte`, contradicting the interface's documented purpose as the *master-key* abstraction. Forcing it through a parallel "InternetPassword chain" would be over-engineering for a single consumer that has no fallback strategies worth chaining. +Forcing Safari through the `Retriever` interface would require returning a different type than `[]byte`, contradicting the interface's documented purpose as the _master-key_ abstraction. Forcing it through a parallel "InternetPassword chain" would be over-engineering for a single consumer that has no fallback strategies worth chaining. -Note the "failure mode" row in particular: Chromium *must* have a master key or extraction fails entirely, so it needs a chain of escalating strategies. Safari can degrade gracefully — if the keychain cannot be unlocked, metadata-only export (URLs and usernames, no plaintext passwords) is still useful output, so a single "try keychainbreaker, warn on failure" is sufficient. +Note the "failure mode" row in particular: Chromium _must_ have a master key or extraction fails entirely, so it needs a chain of escalating strategies. Safari can degrade gracefully — if the keychain cannot be unlocked, metadata-only export (URLs and usernames, no plaintext passwords) is still useful output, so a single "try keychainbreaker, warn on failure" is sufficient. ### 7.2 The General Rule @@ -206,7 +207,7 @@ Note the "failure mode" row in particular: Chromium *must* have a master key or Evidence the rule is already in force: -- **Firefox** (`browser/firefox/firefox.go`) does not import `masterkey` or `keychainbreaker`. It derives keys from `key4.db` via internal NSS PBE. See RFC-005. +- **Firefox** (`browser/firefox/firefox.go`) does not import `masterkey` or `keychainbreaker`. It derives keys from `key4.db` via internal NSS PBE. See RFC-019. - **Safari** (`browser/safari/extract_password.go`) uses `keychainbreaker` directly for `InternetPassword` records. - **Chromium variants** all go through `masterkey` because they share exactly one chain and benefit from the shared `sync.Once` caching. @@ -216,10 +217,10 @@ Future contributors adding a new macOS browser that reads credentials from the K The macOS login password is resolved once at startup by `browser/browser_darwin.go::resolveKeychainPassword`, then delivered to both consumers from within a single platform-specific closure, `newCredentialInjector` (defined per platform in `browser/browser_{darwin,linux,windows}.go`). The closure captures both the retriever chain and the raw password, and applies whichever capability interface each Browser happens to satisfy: -| Consumer | Capability interface | Defined in | Payload | -|---|---|---|---| -| Chromium browsers | `KeyManager` | `browser/browser.go` | `masterkey.Retrievers` struct (V10 / V11 / V20 slots; unused tiers nil) | -| Safari | `KeychainPasswordReceiver` | `browser/browser.go` | raw `string` | +| Consumer | Capability interface | Defined in | Payload | +| ----------------- | -------------------------- | -------------------- | ----------------------------------------------------------------------- | +| Chromium browsers | `KeyManager` | `browser/browser.go` | `masterkey.Retrievers` struct (V10 / V11 / V20 slots; unused tiers nil) | +| Safari | `KeychainPasswordReceiver` | `browser/browser.go` | raw `string` | The two interfaces are **intentionally not unified**. They carry different abstractions — one hands the browser a pre-assembled retrieval chain, the other hands the browser a credential token to unlock its own access path. Unifying them would create a leaky polymorphic interface with no real shared semantics. @@ -235,7 +236,7 @@ The two interfaces are **intentionally not unified**. They carry different abstr ## Related RFCs -| RFC | Topic | -|-----|-------| -| [RFC-003](003-chromium-encryption.md) | Chromium encryption mechanisms per platform | -| [RFC-005](005-firefox-encryption.md) | Firefox NSS encryption and key derivation | +| RFC | Topic | +| ------------------------------------- | ------------------------------------------- | +| [RFC-014](014-chromium-encryption.md) | Chromium encryption mechanisms per platform | +| [RFC-019](019-firefox-encryption.md) | Firefox NSS encryption and key derivation | diff --git a/rfcs/010-chrome-abe-integration.md b/rfcs/016-chrome-abe-integration.md similarity index 71% rename from rfcs/010-chrome-abe-integration.md rename to rfcs/016-chrome-abe-integration.md index 14a5ae4..5ac5bd6 100644 --- a/rfcs/010-chrome-abe-integration.md +++ b/rfcs/016-chrome-abe-integration.md @@ -1,6 +1,9 @@ -# RFC-010: Chrome App-Bound Encryption Integration +# RFC-016: Chrome App-Bound Encryption Integration -**Author**: moonD4rk **Status**: Living Document **Created**: 2026-04-17 **Last updated**: 2026-04-19 +**Author**: moonD4rk\ +**Status**: Living Document\ +**Created**: 2026-04-17\ +**Last updated**: 2026-04-19 ## 1. Overview @@ -10,9 +13,9 @@ This RFC documents how HackBrowserData integrates ABE support end-to-end while k Related RFCs: -- [RFC-003](003-chromium-encryption.md) — cipher versions (v10, v11, v20) -- [RFC-006](006-key-retrieval-mechanisms.md) — `Retriever` / `ChainRetriever` -- [RFC-009](009-windows-locked-file-bypass.md) — other Windows-specific handling +- [RFC-014](014-chromium-encryption.md) — cipher versions (v10, v11, v20) +- [RFC-015](015-key-retrieval-mechanisms.md) — `Retriever` / `ChainRetriever` +- [RFC-021](021-windows-locked-file-bypass.md) — other Windows-specific handling ### 1.1 Compatibility contract @@ -106,15 +109,15 @@ Three translation units, ~500 lines of pure C. No C++, no assembly, no direct sy Structure after refactor: **one ~30-line orchestrator + seven single-purpose static helpers**: -| Helper | Responsibility | -| --- | --- | -| `locate_own_image_base` | Backward-scan from `__builtin_return_address(0)` for MZ/PE magic (must stay `noinline`) | -| `read_bootstrap_params` | Read the standalone scratch pointer and 5 function pointers from the remote parameter block (§4.4) | -| `allocate_and_copy_image` | `VirtualAlloc(SizeOfImage, RW)` + copy headers/sections | -| `apply_base_relocations` | Walk `IMAGE_DIRECTORY_ENTRY_BASERELOC`, fix `IMAGE_REL_BASED_DIR64` | -| `link_iat` | Resolve each imported DLL + fill IAT via parameter-supplied `LoadLibraryA` / `GetProcAddress` | -| `set_section_protections` | `.text → RX`, `.rdata → R`, `.data → RW` per `Characteristics` | -| `invoke_dllmain` | Call mapped `DllMain(DLL_PROCESS_ATTACH, scratchBase)` | +| Helper | Responsibility | +| ------------------------- | -------------------------------------------------------------------------------------------------- | +| `locate_own_image_base` | Backward-scan from `__builtin_return_address(0)` for MZ/PE magic (must stay `noinline`) | +| `read_bootstrap_params` | Read the standalone scratch pointer and 5 function pointers from the remote parameter block (§4.4) | +| `allocate_and_copy_image` | `VirtualAlloc(SizeOfImage, RW)` + copy headers/sections | +| `apply_base_relocations` | Walk `IMAGE_DIRECTORY_ENTRY_BASERELOC`, fix `IMAGE_REL_BASED_DIR64` | +| `link_iat` | Resolve each imported DLL + fill IAT via parameter-supplied `LoadLibraryA` / `GetProcAddress` | +| `set_section_protections` | `.text → RX`, `.rdata → R`, `.data → RW` per `Characteristics` | +| `invoke_dllmain` | Call mapped `DllMain(DLL_PROCESS_ATTACH, scratchBase)` | Progress markers: after each major step the orchestrator writes one byte to `scratchBase + BOOTSTRAP_MARKER_OFFSET` (0x28). The Go injector reads this back on failure to pinpoint the stage. @@ -167,12 +170,12 @@ Validity relies on Windows **KnownDlls + session-consistent ASLR** — `kernel32 Four files collaborate: -| File | Role | -| --- | --- | +| File | Role | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `reflective_windows.go` | `Reflective.Inject(exePath, payload, env) ([]byte, error)` — the orchestrator. Win32 calls (`VirtualAllocEx`, `VirtualProtectEx`, `CreateRemoteThread`, import-address lookups) delegate to `utils/winapi/` via `CallBoolErr`. | -| `errors_windows.go` | `formatABEError(scratchResult) string` — renders the C-side diag channel into human-readable strings via two lookup maps (`ABE_ERR_*` names + known HRESULT names like `E_ACCESSDENIED`). | -| `pe_windows.go` | `FindExportFileOffset(dllBytes, "Bootstrap")` — raw-file offset via `debug/pe`. | -| `arch_windows.go` | Architecture validation (amd64-only today). | +| `errors_windows.go` | `formatABEError(scratchResult) string` — renders the C-side diag channel into human-readable strings via two lookup maps (`ABE_ERR_*` names + known HRESULT names like `E_ACCESSDENIED`). | +| `pe_windows.go` | `FindExportFileOffset(dllBytes, "Bootstrap")` — raw-file offset via `debug/pe`. | +| `arch_windows.go` | Architecture validation (amd64-only today). | `scratchResult` is the Go mirror of the remote process's 12-byte diagnostic header: `Marker / Status / ErrCode / HResult / ComErr` + optional 32-byte `Key`. One `ReadProcessMemory` covers the header; a second reads the key only when `Status == KeyStatusReady`. @@ -192,7 +195,7 @@ Go consumes the same constants via **`go tool cgo -godefs`** (a development-time ### 5.3 Retriever wiring & v20 routing -`masterkey.DefaultRetrievers()` on Windows returns a `Retrievers` struct with `V10 = &DPAPIRetriever{}` and `V20 = &ABERetriever{}`. The two tiers are wired independently — not in a ChainRetriever — because a single Chrome profile upgraded from pre-127 can carry mixed v10+v20 ciphertexts, and both keys must be available for `decryptValue` to route each ciphertext to its matching tier (see [RFC-006](006-key-retrieval-mechanisms.md) §4.4 and issue #578). `ABERetriever.RetrieveKey`: +`masterkey.DefaultRetrievers()` on Windows returns a `Retrievers` struct with `V10 = &DPAPIRetriever{}` and `V20 = &ABERetriever{}`. The two tiers are wired independently — not in a ChainRetriever — because a single Chrome profile upgraded from pre-127 can carry mixed v10+v20 ciphertexts, and both keys must be available for `decryptValue` to route each ciphertext to its matching tier (see [RFC-015](015-key-retrieval-mechanisms.md) §4.4 and issue #578). `ABERetriever.RetrieveKey`: 1. Reads `Local State` → extracts `os_crypt.app_bound_encrypted_key` → strips `APPB` prefix. If the field is missing, `ABERetriever` returns `(nil, nil)`, `V20` remains empty, and the independently-wired `V10` DPAPI tier still runs. 2. Resolves browser executable via `utils/winutil/browser_path_windows.go` (registry App Paths → hardcoded fallback). @@ -213,12 +216,12 @@ On extraction success, logs at `Info` level (`abe: retrieved master ke ## 7. Impact on non-Windows contributors — zero -| Scenario | Requires zig? | Requires CGO? | Default `go build ./...` succeeds? | -| --- | --- | --- | --- | -| macOS / Linux feature work | no | no | yes | -| Windows non-ABE (v10/DPAPI) | no | no | yes (stub path) | -| Windows release with ABE | **yes** | no | `make build-windows` | -| CI on any host (non-release) | no | no | yes | +| Scenario | Requires zig? | Requires CGO? | Default `go build ./...` succeeds? | +| ---------------------------- | ------------- | ------------- | ---------------------------------- | +| macOS / Linux feature work | no | no | yes | +| Windows non-ABE (v10/DPAPI) | no | no | yes (stub path) | +| Windows release with ABE | **yes** | no | `make build-windows` | +| CI on any host (non-release) | no | no | yes | All ABE-specific Go code is behind `//go:build windows` (plus `&& abe_embed` for the payload embed). @@ -251,18 +254,18 @@ Import pointers live in the separate `BootstrapParams` block passed as the remot Three implementations of "extract Chrome v20 master key via reflective injection" exist in the ecosystem. -| Dimension | **This project** | **injector-old** (local C++ fork) | **xaitax/Chrome-App-Bound-Encryption-Decryption** | -| --- | --- | --- | --- | -| Top-level language | Go + C | Go + C++ | C++ end-to-end | -| Injector runtime | Go, `CGO_ENABLED=0` | Go, `CGO_ENABLED=0` | C++ standalone exe | -| Reflective loader | **Self-written C**, ~280 lines | Stephen Fewer 2012 `ReflectiveLoader` (vendored C, ~500) | Self-written C++, ~400 | -| kernel32 resolution | **Pre-resolved by Go, passed in BootstrapParams** | PEB walk + `_rotr` hash | PEB walk + `_rotr` hash | -| Syscall mechanism | Win32 APIs | Win32 APIs | Direct syscall via ASM trampoline | -| COM DecryptData dispatch | Vtable slot by browser kind (5/8/13) | Full interface via `ComPtr` | Same as injector-old | -| IPC payload → injector | **env var in, scratch-region read out** | Named pipe (full duplex) | Named pipe (full duplex) | -| Build toolchain for payload | `zig cc` | MSVC / clang-cl | MSVC | -| Runtime disk footprint | **0 bytes** | 1 temp file + pipe | Pipe | -| EDR evasion posture | None (Win32 APIs visible) | Partial (optional Nt\*) | Strong (direct syscalls) | +| Dimension | **This project** | **injector-old** (local C++ fork) | **xaitax/Chrome-App-Bound-Encryption-Decryption** | +| --------------------------- | ------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------- | +| Top-level language | Go + C | Go + C++ | C++ end-to-end | +| Injector runtime | Go, `CGO_ENABLED=0` | Go, `CGO_ENABLED=0` | C++ standalone exe | +| Reflective loader | **Self-written C**, ~280 lines | Stephen Fewer 2012 `ReflectiveLoader` (vendored C, ~500) | Self-written C++, ~400 | +| kernel32 resolution | **Pre-resolved by Go, passed in BootstrapParams** | PEB walk + `_rotr` hash | PEB walk + `_rotr` hash | +| Syscall mechanism | Win32 APIs | Win32 APIs | Direct syscall via ASM trampoline | +| COM DecryptData dispatch | Vtable slot by browser kind (5/8/13) | Full interface via `ComPtr` | Same as injector-old | +| IPC payload → injector | **env var in, scratch-region read out** | Named pipe (full duplex) | Named pipe (full duplex) | +| Build toolchain for payload | `zig cc` | MSVC / clang-cl | MSVC | +| Runtime disk footprint | **0 bytes** | 1 temp file + pipe | Pipe | +| EDR evasion posture | None (Win32 APIs visible) | Partial (optional Nt\*) | Strong (direct syscalls) | ### 9.1 Why we didn't vendor xaitax's Bootstrap @@ -276,11 +279,11 @@ Comparisons in this section were made against [xaitax/Chrome-App-Bound-Encryptio ## 10. Browser coverage -| Browser class | Behavior | -| --- | --- | -| Chrome Stable/Beta, Brave, CocCoc | ABE v20 via `CHROME_BASE` slot (5) | -| Microsoft Edge | ABE v20 via `EDGE` slot (8); v2 `E_NOINTERFACE` → v1 fallback succeeds | -| Avast Secure Browser | ABE v20 via `AVAST` slot (13) | +| Browser class | Behavior | +| ----------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| Chrome Stable/Beta, Brave, CocCoc | ABE v20 via `CHROME_BASE` slot (5) | +| Microsoft Edge | ABE v20 via `EDGE` slot (8); v2 `E_NOINTERFACE` → v1 fallback succeeds | +| Avast Secure Browser | ABE v20 via `AVAST` slot (13) | | Opera / OperaGX / Vivaldi / Yandex / Arc / 360 / QQ / Sogou | Not in `com_iid.c`; legacy v10 cookies still decrypt via DPAPI, v20 cookies do not | Authoritative CLSID/IID table: `crypto/windows/abe_native/com_iid.c`. @@ -316,8 +319,8 @@ Edit `crypto/windows/abe_native/com_iid.c` (add the entry), `utils/winutil/brows ## 13. Related RFCs -| RFC | Relation | -| --- | --- | -| [RFC-003 Chromium Encryption](003-chromium-encryption.md) | v10/v11/v20 cipher format reference; v20 now implemented on Windows per this RFC | -| [RFC-006 Key Retrieval](006-key-retrieval-mechanisms.md) | `masterkey.Retrievers` taxonomy; Windows populates V10 (DPAPI) + V20 (ABE) as independent tier slots | -| [RFC-009 Windows Locked Files](009-windows-locked-file-bypass.md) | Sibling Windows-specific workaround (handle duplication for locked DBs) | +| RFC | Relation | +| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| [RFC-014 Chromium Encryption](014-chromium-encryption.md) | v10/v11/v20 cipher format reference; v20 now implemented on Windows per this RFC | +| [RFC-015 Key Retrieval](015-key-retrieval-mechanisms.md) | `masterkey.Retrievers` taxonomy; Windows populates V10 (DPAPI) + V20 (ABE) as independent tier slots | +| [RFC-021 Windows Locked Files](021-windows-locked-file-bypass.md) | Sibling Windows-specific workaround (handle duplication for locked DBs) | diff --git a/rfcs/012-yandex-decryption.md b/rfcs/017-yandex-decryption.md similarity index 65% rename from rfcs/012-yandex-decryption.md rename to rfcs/017-yandex-decryption.md index 98bf806..d6640b1 100644 --- a/rfcs/012-yandex-decryption.md +++ b/rfcs/017-yandex-decryption.md @@ -1,15 +1,15 @@ -# RFC-012: Yandex Browser Decryption +# RFC-017: Yandex Browser Decryption -**Author**: moonD4rk -**Status**: Living Document -**Created**: 2026-04-22 +**Author**: moonD4rk\ +**Status**: Living Document\ +**Created**: 2026-04-22\ **Last updated**: 2026-04-22 ## 1. Overview Yandex Browser is a Chromium fork, but its saved-credential encryption diverges from the Chromium reference in three ways that together make a plain Chromium extractor produce zero plaintext: -1. The Chromium master key (DPAPI on Windows, Keychain on macOS) does not decrypt `password_value` directly — it decrypts a per-DB *intermediate* key stored in `meta.local_encryptor_data`. That intermediate key is what actually decrypts rows. +1. The Chromium master key (DPAPI on Windows, Keychain on macOS) does not decrypt `password_value` directly — it decrypts a per-DB _intermediate_ key stored in `meta.local_encryptor_data`. That intermediate key is what actually decrypts rows. 2. Each row's AES-GCM ciphertext is sealed with row-specific Additional Authenticated Data (AAD). A password row's AAD is a SHA-1 digest over five form fields joined by `\x00`; a credit-card row's AAD is the row's `guid`. AAD mismatch → GCM tag failure → empty plaintext. 3. Credit cards live in `records(guid, public_data, private_data)` — two JSON blobs — not Chromium's flat `credit_cards` table. @@ -19,8 +19,8 @@ Resolved issues: #90 (feature request), #105 / #462 / #476 (downstream bug repor Related RFCs: -- [RFC-003](003-chromium-encryption.md) — Chromium cipher versions (v10 / v11 / v20) -- [RFC-006](006-key-retrieval-mechanisms.md) — master-key retrieval chain +- [RFC-014](014-chromium-encryption.md) — Chromium cipher versions (v10 / v11 / v20) +- [RFC-015](015-key-retrieval-mechanisms.md) — master-key retrieval chain Deferred to a follow-up RFC / PR: @@ -30,16 +30,16 @@ Deferred to a follow-up RFC / PR: ## 2. Protocol differences at a glance -| Layer | Standard Chromium | Yandex | -|---|---|---| -| Master key | `os_crypt.encrypted_key` in `Local State`, unwrapped via DPAPI / Keychain | Same | -| Decryption key used per row | Master key directly | Intermediate 32-byte key stored per-DB in `meta.local_encryptor_data` | -| Key wrapper format | `"v10"\|nonce\|ct+tag` (or DPAPI blob) | `"v10"\|nonce\|ct+tag`, plaintext prefixed by 4B protobuf signature `08 01 12 20`, 32B key follows | -| Password DB file | `Login Data` (table: `logins`) | `Ya Passman Data` (table: `logins`) | -| Password ciphertext | `"v10"\|nonce\|ct+tag`, AAD = empty | No prefix; raw `nonce\|ct+tag`; AAD = SHA1(origin_url ‖ \x00 ‖ username_element ‖ \x00 ‖ username_value ‖ \x00 ‖ password_element ‖ \x00 ‖ signon_realm) | -| Credit-card DB file | `Web Data` (table: `credit_cards`) | `Ya Credit Cards` (table: `records`) | -| Credit-card layout | Columns: `name_on_card`, `expiration_month`, `card_number_encrypted`, … | JSON: `public_data` (plaintext) + `private_data` (AES-GCM sealed JSON, AAD = `guid`) | -| Master password | n/a | Optional; when set, `active_keys.sealed_key` holds an RSA-OAEP envelope (deferred) | +| Layer | Standard Chromium | Yandex | +| --------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Master key | `os_crypt.encrypted_key` in `Local State`, unwrapped via DPAPI / Keychain | Same | +| Decryption key used per row | Master key directly | Intermediate 32-byte key stored per-DB in `meta.local_encryptor_data` | +| Key wrapper format | `"v10"\|nonce\|ct+tag` (or DPAPI blob) | `"v10"\|nonce\|ct+tag`, plaintext prefixed by 4B protobuf signature `08 01 12 20`, 32B key follows | +| Password DB file | `Login Data` (table: `logins`) | `Ya Passman Data` (table: `logins`) | +| Password ciphertext | `"v10"\|nonce\|ct+tag`, AAD = empty | No prefix; raw `nonce\|ct+tag`; AAD = SHA1(origin_url ‖ \x00 ‖ username_element ‖ \x00 ‖ username_value ‖ \x00 ‖ password_element ‖ \x00 ‖ signon_realm) | +| Credit-card DB file | `Web Data` (table: `credit_cards`) | `Ya Credit Cards` (table: `records`) | +| Credit-card layout | Columns: `name_on_card`, `expiration_month`, `card_number_encrypted`, … | JSON: `public_data` (plaintext) + `private_data` (AES-GCM sealed JSON, AAD = `guid`) | +| Master password | n/a | Optional; when set, `active_keys.sealed_key` holds an RSA-OAEP envelope (deferred) | ## 3. On-disk layout @@ -80,7 +80,7 @@ Same byte shape as passwords but AAD = the row's `guid` bytes (plus optional key ### 4.1 Two-level key hierarchy -Yandex adds a second key layer on top of the standard Chromium key. The Chromium master key — unwrapped from `Local State` via DPAPI (Windows) or Keychain (macOS) — never decrypts row ciphertext directly. Instead, each target SQLite database carries its own *data key* in `meta.local_encryptor_data`, and only that data key decrypts row-level ciphertext. The master key's only job is to unwrap the data key. +Yandex adds a second key layer on top of the standard Chromium key. The Chromium master key — unwrapped from `Local State` via DPAPI (Windows) or Keychain (macOS) — never decrypts row ciphertext directly. Instead, each target SQLite database carries its own _data key_ in `meta.local_encryptor_data`, and only that data key decrypts row-level ciphertext. The master key's only job is to unwrap the data key. ### 4.2 Recovery steps @@ -94,18 +94,18 @@ For every target DB (`Ya Passman Data` for passwords, `Ya Credit Cards` for card ### 4.3 Key hierarchy -| Level | Key | Origin | Scope | -|---|---|---|---| -| 1 | Chromium master key | `Local State` → DPAPI / Keychain | Whole profile (shared with cookies, history, etc.) | -| 2a | Passwords data key | `Ya Passman Data` → `meta.local_encryptor_data` | `logins` rows in this DB only | -| 2b | Credit cards data key | `Ya Credit Cards` → `meta.local_encryptor_data` | `records` rows in this DB only | +| Level | Key | Origin | Scope | +| ----- | --------------------- | ----------------------------------------------- | -------------------------------------------------- | +| 1 | Chromium master key | `Local State` → DPAPI / Keychain | Whole profile (shared with cookies, history, etc.) | +| 2a | Passwords data key | `Ya Passman Data` → `meta.local_encryptor_data` | `logins` rows in this DB only | +| 2b | Credit cards data key | `Ya Credit Cards` → `meta.local_encryptor_data` | `records` rows in this DB only | ### 4.4 Per-category decryption inputs -| Category | DB file | Table / column | Ciphertext layout | AAD | -|---|---|---|---|---| -| Password | `Ya Passman Data` | `logins.password_value` | `[12B nonce][ct+tag]` | `SHA1(origin_url ‖ \x00 ‖ username_element ‖ \x00 ‖ username_value ‖ \x00 ‖ password_element ‖ \x00 ‖ signon_realm)` | -| Credit card | `Ya Credit Cards` | `records.private_data` | `[12B nonce][ct+tag]` | raw `guid` bytes | +| Category | DB file | Table / column | Ciphertext layout | AAD | +| ----------- | ----------------- | ----------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------- | +| Password | `Ya Passman Data` | `logins.password_value` | `[12B nonce][ct+tag]` | `SHA1(origin_url ‖ \x00 ‖ username_element ‖ \x00 ‖ username_value ‖ \x00 ‖ password_element ‖ \x00 ‖ signon_realm)` | +| Credit card | `Ya Credit Cards` | `records.private_data` | `[12B nonce][ct+tag]` | raw `guid` bytes | Credit-card plaintext is a JSON object (`full_card_number`, `pin_code`, `secret_comment`) that the extractor unmarshals into `CreditCardEntry`. The sibling `records.public_data` is plaintext JSON (`card_holder`, `card_title`, `expire_date_year`, `expire_date_month`) and needs no decryption. @@ -133,12 +133,12 @@ The final split: - A single generic AES-GCM-with-AAD primitive in the crypto layer. Any current or future protocol that needs per-row AAD can reuse it without the crypto layer growing per-product surface. - Yandex-specific AAD helpers next to the consumer that builds the AAD inputs. Product knowledge stays with the product. -This keeps the crypto surface minimal — the only Yandex symbol it owns is the intermediate-key unwrap, because that one function genuinely *is* cryptography (it strips a protobuf frame and decrypts AES-GCM). +This keeps the crypto surface minimal — the only Yandex symbol it owns is the intermediate-key unwrap, because that one function genuinely _is_ cryptography (it strips a protobuf frame and decrypts AES-GCM). ## 6. Non-goals and deferred work 1. **Master-password unseal** (#90 edge case). Profiles with a non-empty `active_keys.sealed_key` are detected and skipped with a warning. A follow-up RFC will cover the RSA-OAEP path: PBKDF2-SHA256 derives a KEK; the KEK decrypts `encrypted_private_key` with AAD = `unlock_key_salt`; the resulting PKCS8 RSA private key + RSA-OAEP-SHA256 decrypts `encrypted_encryption_key`; the signature strip then yields the dataKey. -2. **Windows ABE v20 for Yandex**. Yandex has not adopted App-Bound Encryption. If that changes, Yandex joins the RFC-010 vendor table and the ABE path begins returning a non-empty v20 key for Yandex ciphertexts. +2. **Windows ABE v20 for Yandex**. Yandex has not adopted App-Bound Encryption. If that changes, Yandex joins the RFC-016 vendor table and the ABE path begins returning a non-empty v20 key for Yandex ciphertexts. 3. **Linux support**. Yandex Browser has no official Linux release, so there is no Linux code path to add. ## 7. Test strategy diff --git a/rfcs/004-firefox-data-storage.md b/rfcs/018-firefox-data-storage.md similarity index 54% rename from rfcs/004-firefox-data-storage.md rename to rfcs/018-firefox-data-storage.md index 5df3c93..8760ef8 100644 --- a/rfcs/004-firefox-data-storage.md +++ b/rfcs/018-firefox-data-storage.md @@ -1,7 +1,7 @@ -# RFC-004: Firefox Data Storage +# RFC-018: Firefox Data Storage -**Author**: moonD4rk -**Status**: Living Document +**Author**: moonD4rk\ +**Status**: Living Document\ **Created**: 2026-04-05 ## 1. Profile Structure @@ -14,19 +14,19 @@ Profile discovery enumerates subdirectories of the root and accepts any director All paths are relative to the profile directory. -| Category | File | Format | -|----------|------|--------| -| Password | `logins.json` | JSON | -| Cookie | `cookies.sqlite` | SQLite | -| History | `places.sqlite` | SQLite | -| Download | `places.sqlite` | SQLite | -| Bookmark | `places.sqlite` | SQLite | -| Extension | `extensions.json` | JSON | +| Category | File | Format | +| ------------ | --------------------- | ------ | +| Password | `logins.json` | JSON | +| Cookie | `cookies.sqlite` | SQLite | +| History | `places.sqlite` | SQLite | +| Download | `places.sqlite` | SQLite | +| Bookmark | `places.sqlite` | SQLite | +| Extension | `extensions.json` | JSON | | LocalStorage | `webappsstore.sqlite` | SQLite | History, Download, and Bookmark all share `places.sqlite` but query different tables within it. Firefox does not support CreditCard or SessionStorage extraction. -The master encryption key is stored separately in `key4.db` (see [RFC-005](005-firefox-encryption.md)). +The master encryption key is stored separately in `key4.db` (see [RFC-019](019-firefox-encryption.md)). ## 3. Data Storage Formats @@ -98,33 +98,33 @@ The `originKey` column uses a **reversed-host format**: `moc.buhtig.:https:443` Firefox uses inconsistent timestamp units across data types. All are Unix epoch-based. -| Data Type | Unit | Conversion | -|-----------|------|------------| -| Cookies (`creationTime`) | Microseconds | / 1,000,000 | -| Cookies (`expiry`) | Seconds | direct | +| Data Type | Unit | Conversion | +| --------------------------- | ------------ | ----------- | +| Cookies (`creationTime`) | Microseconds | / 1,000,000 | +| Cookies (`expiry`) | Seconds | direct | | History (`last_visit_date`) | Microseconds | / 1,000,000 | -| Downloads (`dateAdded`) | Microseconds | / 1,000,000 | -| Downloads (`endTime`) | Milliseconds | / 1,000 | -| Bookmarks (`dateAdded`) | Microseconds | / 1,000,000 | -| Passwords (`timeCreated`) | Milliseconds | / 1,000 | +| Downloads (`dateAdded`) | Microseconds | / 1,000,000 | +| Downloads (`endTime`) | Milliseconds | / 1,000 | +| Bookmarks (`dateAdded`) | Microseconds | / 1,000,000 | +| Passwords (`timeCreated`) | Milliseconds | / 1,000 | ## 5. Key Differences from Chromium -| Aspect | Chromium | Firefox | -|--------|----------|---------| -| Profile naming | Named directories (`Default`, `Profile 1`) | Random-prefix (`97nszz88.default-release`) | -| Profile detection | `Preferences` sentinel file | Any known source file present | -| Password storage | SQLite (`Login Data`) | JSON (`logins.json`) | -| Cookie encryption | Encrypted with master key | **Plaintext** | -| Shared database | Separate files per category | `places.sqlite` shared by History/Download/Bookmark | -| LocalStorage | LevelDB | SQLite (`webappsstore.sqlite`) | -| CreditCard support | Yes | No | -| SessionStorage support | Yes | No | -| Encryption scope | Passwords, cookies, credit cards | **Passwords only** (see [RFC-005](005-firefox-encryption.md)) | +| Aspect | Chromium | Firefox | +| ---------------------- | ------------------------------------------ | ------------------------------------------------------------- | +| Profile naming | Named directories (`Default`, `Profile 1`) | Random-prefix (`97nszz88.default-release`) | +| Profile detection | `Preferences` sentinel file | Any known source file present | +| Password storage | SQLite (`Login Data`) | JSON (`logins.json`) | +| Cookie encryption | Encrypted with master key | **Plaintext** | +| Shared database | Separate files per category | `places.sqlite` shared by History/Download/Bookmark | +| LocalStorage | LevelDB | SQLite (`webappsstore.sqlite`) | +| CreditCard support | Yes | No | +| SessionStorage support | Yes | No | +| Encryption scope | Passwords, cookies, credit cards | **Passwords only** (see [RFC-019](019-firefox-encryption.md)) | ## Related RFCs -| RFC | Topic | -|-----|-------| -| [RFC-005](005-firefox-encryption.md) | Firefox NSS encryption and master key derivation | -| [RFC-008](008-file-acquisition-and-platform-quirks.md) | File acquisition and platform quirks | +| RFC | Topic | +| ------------------------------------------ | ------------------------------------------------ | +| [RFC-019](019-firefox-encryption.md) | Firefox NSS encryption and master key derivation | +| [RFC-007](007-snapshot-and-acquisition.md) | Snapshot-first file acquisition | diff --git a/rfcs/005-firefox-encryption.md b/rfcs/019-firefox-encryption.md similarity index 78% rename from rfcs/005-firefox-encryption.md rename to rfcs/019-firefox-encryption.md index de5ae44..cd6db52 100644 --- a/rfcs/005-firefox-encryption.md +++ b/rfcs/019-firefox-encryption.md @@ -1,14 +1,14 @@ -# RFC-005: Firefox Encryption +# RFC-019: Firefox Encryption -**Author**: moonD4rk -**Status**: Living Document +**Author**: moonD4rk\ +**Status**: Living Document\ **Created**: 2026-04-05 ## 1. Overview Firefox uses Mozilla's NSS (Network Security Services) for credential encryption. Unlike Chromium, which delegates key storage to the OS (DPAPI, Keychain, D-Bus), Firefox manages its own encryption entirely within the profile directory via `key4.db`. This makes Firefox encryption **platform-agnostic** — the same derivation logic works on Windows, macOS, and Linux. -Only passwords are encrypted. Cookies, history, bookmarks, downloads, extensions, and localStorage are all stored in plaintext. See [RFC-004](004-firefox-data-storage.md) for storage details. +Only passwords are encrypted. Cookies, history, bookmarks, downloads, extensions, and localStorage are all stored in plaintext. See [RFC-018](018-firefox-data-storage.md) for storage details. ## 2. Master Key Derivation (key4.db) @@ -16,10 +16,10 @@ Only passwords are encrypted. Cookies, history, bookmarks, downloads, extensions `key4.db` is a SQLite database containing two relevant tables: -| Table | Purpose | Key Columns | -|-------|---------|-------------| -| `metaData` | Stores the global salt and an encrypted integrity marker | `item1` (global salt), `item2` (encrypted "password-check" string) | -| `nssPrivate` | Stores encrypted master key candidates | `a11` (PBE-encrypted key blob), `a102` (key type tag) | +| Table | Purpose | Key Columns | +| ------------ | -------------------------------------------------------- | ------------------------------------------------------------------ | +| `metaData` | Stores the global salt and an encrypted integrity marker | `item1` (global salt), `item2` (encrypted "password-check" string) | +| `nssPrivate` | Stores encrypted master key candidates | `a11` (PBE-encrypted key blob), `a102` (key type tag) | The `nssPrivate` table may contain multiple rows (certificates, other NSS objects). Only rows where `a102` matches a specific 16-byte type tag (`{0xF8, 0x00, ...0x01}`) are actual master key entries. @@ -34,11 +34,11 @@ The `nssPrivate` table may contain multiple rows (certificates, other NSS object Firefox wraps all encrypted data in ASN1 structures. Three PBE (Password-Based Encryption) types are used, each with a distinct ASN1 layout: -| PBE Type | Used For | Cipher | Key Derivation | -|----------|----------|--------|----------------| -| `privateKeyPBE` | Master key entries in `nssPrivate` | 3DES-CBC | SHA1 + HMAC-SHA1 custom NSS derivation | -| `passwordCheckPBE` | Integrity marker in `metaData` | AES-256-CBC | PBKDF2-SHA256 | -| `credentialPBE` | Encrypted fields in `logins.json` | 3DES-CBC or AES-256-CBC | Master key used directly (no derivation) | +| PBE Type | Used For | Cipher | Key Derivation | +| ------------------ | ---------------------------------- | ----------------------- | ---------------------------------------- | +| `privateKeyPBE` | Master key entries in `nssPrivate` | 3DES-CBC | SHA1 + HMAC-SHA1 custom NSS derivation | +| `passwordCheckPBE` | Integrity marker in `metaData` | AES-256-CBC | PBKDF2-SHA256 | +| `credentialPBE` | Encrypted fields in `logins.json` | 3DES-CBC or AES-256-CBC | Master key used directly (no derivation) | The `key` parameter has different semantics depending on the PBE type: @@ -77,6 +77,7 @@ Legacy Firefox versions encrypt login credentials with 3DES-CBC. The `credential ``` Decryption details: + - **Key**: the first 24 bytes of the master key (derived from `key4.db`, see Section 2) - **IV**: 8-byte IV embedded in the ASN1 structure - **Algorithm**: Triple DES in CBC mode with PKCS5 padding @@ -103,6 +104,7 @@ Starting from [Firefox 144](https://www.firefox.com/en-US/firefox/144.0/releasen ``` Decryption details: + - **Key**: the full master key (32 bytes for AES-256) - **IV**: 16-byte IV embedded in the ASN1 structure - **Algorithm**: AES-256 in CBC mode with PKCS5 padding @@ -136,7 +138,7 @@ The master key is passed through unchanged — `credentialPBE` uses the key dire ## Related RFCs -| RFC | Topic | -|-----|-------| -| [RFC-004](004-firefox-data-storage.md) | Firefox data file locations and storage formats | -| [RFC-006](006-key-retrieval-mechanisms.md) | Platform-specific master key retrieval (Chromium only — Firefox is self-contained) | +| RFC | Topic | +| ------------------------------------------ | ---------------------------------------------------------------------------------- | +| [RFC-018](018-firefox-data-storage.md) | Firefox data file locations and storage formats | +| [RFC-015](015-key-retrieval-mechanisms.md) | Platform-specific master key retrieval (Chromium only — Firefox is self-contained) | diff --git a/rfcs/011-safari-data-storage.md b/rfcs/020-safari-data-storage.md similarity index 54% rename from rfcs/011-safari-data-storage.md rename to rfcs/020-safari-data-storage.md index 1d30f28..6acf3a3 100644 --- a/rfcs/011-safari-data-storage.md +++ b/rfcs/020-safari-data-storage.md @@ -1,14 +1,14 @@ -# RFC-011: Safari Data Storage +# RFC-020: Safari Data Storage -**Author**: moonD4rk -**Status**: Living Document +**Author**: moonD4rk\ +**Status**: Living Document\ **Created**: 2026-04-21 ## 1. Overview Safari is **macOS-only** and sandboxed under App Sandbox. Most of Safari's user data lives inside `~/Library/Containers/com.apple.Safari/Data/Library/` (the container root) and requires **Full Disk Access (TCC)** for third-party processes to read. A few legacy files still reside at `~/Library/Safari/` for backwards compatibility. -Unlike Chromium and Firefox, Safari does **not** encrypt bookmarks, history, cookies, downloads, or localStorage — all are stored in plaintext on disk. Passwords are the only encrypted category and are delegated to the macOS login Keychain (see [RFC-006](006-key-retrieval-mechanisms.md) §7). +Unlike Chromium and Firefox, Safari does **not** encrypt bookmarks, history, cookies, downloads, or localStorage — all are stored in plaintext on disk. Passwords are the only encrypted category and are delegated to the macOS login Keychain (see [RFC-015](015-key-retrieval-mechanisms.md) §7). Safari 17 (September 2023) introduced **multi-profile support**. Profile discovery therefore has two layers: a synthetic "default" profile mapped to the pre-profile legacy paths, plus one or more named profiles enumerated from `SafariTabs.db`. @@ -16,13 +16,13 @@ Safari 17 (September 2023) introduced **multi-profile support**. Profile discove Each `profileContext` (in `browser/safari/profiles.go`) tracks five fields: -| Field | Meaning | -|-------|---------| -| `name` | Human-readable profile name, disambiguated for duplicates | -| `uuidUpper` | UUID in uppercase (used by `Safari/Profiles//` directories) | -| `uuidLower` | UUID in lowercase (used by `WebKit/WebsiteDataStore//` directories) | -| `legacyHome` | `~/Library/Safari` | -| `container` | `~/Library/Containers/com.apple.Safari/Data/Library` | +| Field | Meaning | +| ------------ | ------------------------------------------------------------------------- | +| `name` | Human-readable profile name, disambiguated for duplicates | +| `uuidUpper` | UUID in uppercase (used by `Safari/Profiles//` directories) | +| `uuidLower` | UUID in lowercase (used by `WebKit/WebsiteDataStore//` directories) | +| `legacyHome` | `~/Library/Safari` | +| `container` | `~/Library/Containers/com.apple.Safari/Data/Library` | Empty `uuidUpper` marks the synthetic default profile. @@ -45,9 +45,9 @@ Duplicate display names are disambiguated with `-2`, `-3`, … suffixes, determi Safari uses two different casings for the same profile UUID across the container: -| Path prefix | Casing | Example | -|-------------|:------:|---------| -| `Safari/Profiles//` | Uppercase | `5604E6F5-02ED-4E40-8249-63DE7BC986C8` | +| Path prefix | Casing | Example | +| --------------------------------- | :-------: | -------------------------------------- | +| `Safari/Profiles//` | Uppercase | `5604E6F5-02ED-4E40-8249-63DE7BC986C8` | | `WebKit/WebsiteDataStore//` | Lowercase | `5604e6f5-02ed-4e40-8249-63de7bc986c8` | `profileContext` stores both to avoid case-folding at every call site. @@ -56,26 +56,26 @@ Safari uses two different casings for the same profile UUID across the container ### 3.1 Default Profile -| Category | Path | Format | -|----------|------|--------| -| History | `~/Library/Safari/History.db` | SQLite | -| Cookie | `Container/Cookies/Cookies.binarycookies`, then `~/Library/Cookies/Cookies.binarycookies` | BinaryCookies | -| Bookmark | `~/Library/Safari/Bookmarks.plist` | plist | -| Download | `~/Library/Safari/Downloads.plist` | plist | -| Extension | `Container/Safari/AppExtensions/Extensions.plist`, `Container/Safari/WebExtensions/Extensions.plist` | plist | -| LocalStorage | `Container/WebKit/WebsiteData/Default/` | WebKit Origins dir | -| Password | macOS Keychain | — | +| Category | Path | Format | +| ------------ | ---------------------------------------------------------------------------------------------------- | ------------------ | +| History | `~/Library/Safari/History.db` | SQLite | +| Cookie | `Container/Cookies/Cookies.binarycookies`, then `~/Library/Cookies/Cookies.binarycookies` | BinaryCookies | +| Bookmark | `~/Library/Safari/Bookmarks.plist` | plist | +| Download | `~/Library/Safari/Downloads.plist` | plist | +| Extension | `Container/Safari/AppExtensions/Extensions.plist`, `Container/Safari/WebExtensions/Extensions.plist` | plist | +| LocalStorage | `Container/WebKit/WebsiteData/Default/` | WebKit Origins dir | +| Password | macOS Keychain | — | The Cookie path is resolved in priority order — the first candidate that exists wins. Modern (macOS 14+) installs keep cookies in the sandboxed container; the legacy path is kept as a fallback for upgraded systems. ### 3.2 Named Profiles -| Category | Path | Format | -|----------|------|--------| -| History | `Container/Safari/Profiles//History.db` | SQLite | -| Cookie | `Container/WebKit/WebsiteDataStore//Cookies/Cookies.binarycookies` | BinaryCookies | -| Download | `~/Library/Safari/Downloads.plist` (filtered by UUID) | plist | -| LocalStorage | `Container/WebKit/WebsiteDataStore//Origins/` | WebKit Origins dir | +| Category | Path | Format | +| ------------ | ------------------------------------------------------------------------ | ------------------ | +| History | `Container/Safari/Profiles//History.db` | SQLite | +| Cookie | `Container/WebKit/WebsiteDataStore//Cookies/Cookies.binarycookies` | BinaryCookies | +| Download | `~/Library/Safari/Downloads.plist` (filtered by UUID) | plist | +| LocalStorage | `Container/WebKit/WebsiteDataStore//Origins/` | WebKit Origins dir | Bookmark is intentionally **omitted** from named profiles: `Bookmarks.plist` is a shared plist with no per-entry profile tag, so it is attributed to the default profile only. Duplicate bookmarks would otherwise be emitted per profile. @@ -98,6 +98,7 @@ LEFT JOIN history_visits hv ON hv.id = ( ``` Schema notes: + - `visit_time` is a `REAL` column using the **Core Data epoch** (see Section 5) - One item → many visits; the extractor takes the most recent visit per item - Results are sorted by `visit_count` descending @@ -122,9 +123,9 @@ Cookie values are **plaintext** — no per-cookie encryption. This is a fundamen A nested dictionary tree with a `WebBookmarkType` discriminator at each node: -| Type | Meaning | Additional keys | -|------|---------|-----------------| -| `WebBookmarkTypeList` | Folder | `Children` (array) | +| Type | Meaning | Additional keys | +| --------------------- | --------- | ---------------------------------- | +| `WebBookmarkTypeList` | Folder | `Children` (array) | | `WebBookmarkTypeLeaf` | URL entry | `URLString`, `URIDictionary.title` | The extractor walks the tree recursively, collecting leaf nodes into a flat list. Folder names are preserved in the `Folder` field of each `BookmarkEntry`. @@ -133,11 +134,11 @@ The extractor walks the tree recursively, collecting leaf nodes into a flat list A flat structure with a `DownloadHistory` array. Relevant keys per entry: -| Key | Meaning | -|-----|---------| -| `DownloadEntryURL` | Source URL | -| `DownloadEntryPath` | Local filesystem path | -| `DownloadEntryProgressTotalToLoad` | Total bytes to download | +| Key | Meaning | +| ----------------------------------- | ------------------------------------------------------ | +| `DownloadEntryURL` | Source URL | +| `DownloadEntryPath` | Local filesystem path | +| `DownloadEntryProgressTotalToLoad` | Total bytes to download | | `DownloadEntryProfileUUIDStringKey` | Owning profile's uppercase UUID, or `"DefaultProfile"` | The extractor filters by the caller-provided owner UUID so each profile reports its own downloads. MIME type and start/end times are not stored by Safari — `MimeType` is always empty in the output. @@ -148,25 +149,25 @@ Safari does **not** persist passwords to a file in its container. All credential Default port handling: -| Protocol | Default port | URL rendering | -|----------|-------------:|---------------| -| `https` | 443 | `https://host/path` (port omitted) | -| `http` | 80 | `http://host/path` (port omitted) | -| `ftp` | 21 | `ftp://host/path` (port omitted) | -| Other | — | `scheme://host:port/path` | +| Protocol | Default port | URL rendering | +| -------- | -----------: | ---------------------------------- | +| `https` | 443 | `https://host/path` (port omitted) | +| `http` | 80 | `http://host/path` (port omitted) | +| `ftp` | 21 | `ftp://host/path` (port omitted) | +| Other | — | `scheme://host:port/path` | The `htps` FourCC protocol code emitted by some Keychain entries is normalized to `https`. -Partial-extraction mode: if the Keychain cannot be unlocked (no `--keychain-pw` supplied, or the password is wrong), metadata-only records are still emitted — URL, username, timestamps — with `PlainPassword` left blank. See [RFC-006](006-key-retrieval-mechanisms.md) §7 for the full credential-extraction architecture. +Partial-extraction mode: if the Keychain cannot be unlocked (no `--keychain-pw` supplied, or the password is wrong), metadata-only records are still emitted — URL, username, timestamps — with `PlainPassword` left blank. See [RFC-015](015-key-retrieval-mechanisms.md) §7 for the full credential-extraction architecture. ### 4.6 LocalStorage (WebKit Origins — nested SQLite) Safari 17+ stores localStorage under a **partition-aware nested tree**, rooted at: -| Profile | Root path | -|---------|-----------| -| Default | `Container/WebKit/WebsiteData/Default/` | -| Named | `Container/WebKit/WebsiteDataStore//Origins/` | +| Profile | Root path | +| ------- | --------------------------------------------------- | +| Default | `Container/WebKit/WebsiteData/Default/` | +| Named | `Container/WebKit/WebsiteDataStore//Origins/` | Under the root, two levels of hashed directories lead to the actual data: @@ -209,19 +210,19 @@ SELECT key, value FROM ItemTable Schema: `(key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`. -Values are **UTF-16 LE** encoded JS strings. Oversized values (≥ 2048 bytes) are replaced with a size marker in the output — this matches the cap used by the Chromium extractor ([RFC-002](002-chromium-data-storage.md) §4.8) and keeps JSON/CSV exports bounded. +Values are **UTF-16 LE** encoded JS strings. Oversized values (≥ 2048 bytes) are replaced with a size marker in the output — this matches the cap used by the Chromium extractor ([RFC-013](013-chromium-data-storage.md) §4.8) and keeps JSON/CSV exports bounded. ## 5. Time Formats Safari uses the **Core Data epoch** — 2001-01-01 00:00:00 UTC, which is **978,307,200 seconds** after the Unix epoch. To convert a Core Data timestamp to Unix time, add `978307200` seconds. -| Data Type | Field | Storage | -|-----------|-------|---------| -| History | `visit_time` | REAL seconds, Core Data epoch | -| Cookies | `creation`, `expiry` | REAL seconds, Core Data epoch | -| Downloads | — | No timestamp stored | -| Passwords | Keychain `Created` | Already Unix time (via keychainbreaker) | -| LocalStorage | — | No timestamp stored | +| Data Type | Field | Storage | +| ------------ | -------------------- | --------------------------------------- | +| History | `visit_time` | REAL seconds, Core Data epoch | +| Cookies | `creation`, `expiry` | REAL seconds, Core Data epoch | +| Downloads | — | No timestamp stored | +| Passwords | Keychain `Created` | Already Unix time (via keychainbreaker) | +| LocalStorage | — | No timestamp stored | Bookmarks carry no timestamp in Safari's plist representation. @@ -229,16 +230,16 @@ Bookmarks carry no timestamp in Safari's plist representation. Safari's encryption story is deliberately thin: -| Category | Encryption | -|----------|------------| -| History | None (plaintext SQLite) | -| Cookies | None (plaintext binary format) | -| Bookmarks | None (plaintext plist) | -| Downloads | None (plaintext plist) | -| LocalStorage | None (plaintext SQLite; UTF-16 LE is an encoding, not encryption) | -| Passwords | macOS Keychain — see [RFC-006](006-key-retrieval-mechanisms.md) §7 | +| Category | Encryption | +| ------------ | ------------------------------------------------------------------ | +| History | None (plaintext SQLite) | +| Cookies | None (plaintext binary format) | +| Bookmarks | None (plaintext plist) | +| Downloads | None (plaintext plist) | +| LocalStorage | None (plaintext SQLite; UTF-16 LE is an encoding, not encryption) | +| Passwords | macOS Keychain — see [RFC-015](015-key-retrieval-mechanisms.md) §7 | -The only encrypted category is passwords. Because they are not stored in Safari's own files at all, there is no Safari-specific cipher, key derivation, or master-key retrieval to document. See RFC-006 for the `InternetPassword` extraction path. +The only encrypted category is passwords. Because they are not stored in Safari's own files at all, there is no Safari-specific cipher, key derivation, or master-key retrieval to document. See RFC-015 for the `InternetPassword` extraction path. ## 7. Platform Specifics @@ -248,31 +249,31 @@ The only encrypted category is passwords. Because they are not stored in Safari' - **Live reads** (`SafariTabs.db` during profile discovery in `profiles.go`) use `?mode=ro&immutable=1`, which disables WAL replay and locking so the extractor cannot disturb a running Safari — it sees a consistent snapshot of the main DB as of read time, at the cost of missing any pending WAL content. - **Temp-copy reads** (via `filemanager.Session.Acquire`) vary by file: `localstorage.sqlite3` uses `?mode=ro` so SQLite can replay the copied `-wal` sidecar; `History.db` opens with `PRAGMA journal_mode=off` (WAL replay not needed for read-only history queries). `Session.Acquire` copies the `-wal` / `-shm` sidecars alongside the main DB. Any `-shm` writes SQLite performs during replay land on the ephemeral copy and are deleted with the session. - **Multi-profile availability**: requires Safari 17 (macOS 14 Sonoma) or newer. Older Safari versions have only the default profile; discovery degrades cleanly via the ReadDir fallback described in §2.1. -- **File acquisition**: all per-profile files are copied into a `filemanager.Session` temp directory before extraction, except the discovery-time `SafariTabs.db` read which opens the live file directly. See [RFC-008](008-file-acquisition-and-platform-quirks.md) for the general pattern. +- **File acquisition**: all per-profile files are copied into a `filemanager.Session` temp directory before extraction, except the discovery-time `SafariTabs.db` read which opens the live file directly. See [RFC-007](007-snapshot-and-acquisition.md) for the general pattern. ## 8. Key Differences from Chromium and Firefox -| Aspect | Chromium | Firefox | Safari | -|--------|----------|---------|--------| -| Platform | Cross-platform | Cross-platform | **macOS-only** | -| Profile discovery | `Preferences` sentinel file | Any data file present | `SafariTabs.db` SQL + dir fallback | -| Profile naming | `Default`, `Profile 1`, … | `.default-release` | Human-readable title from SafariTabs.db | -| Password storage | Encrypted SQLite (`Login Data`) | Encrypted JSON (`logins.json`) | **macOS Keychain** (no file) | -| Cookie encryption | Encrypted with OS master key | Plaintext | **Plaintext** | -| Cookie format | SQLite | SQLite | Proprietary BinaryCookies binary | -| History | SQLite | SQLite (`places.sqlite`) | SQLite (Core Data epoch) | -| Bookmark | JSON | SQLite (`places.sqlite`) | **plist** | -| Download | SQLite (`History`, shared) | SQLite (`places.sqlite`, shared) | **plist** (filtered by UUID) | -| LocalStorage | LevelDB | SQLite (`webappsstore.sqlite`) | Nested **WebKit Origins** SQLite | -| LocalStorage partitioning | No | No | **Yes** (top-frame + frame hashes) | -| CreditCard / SessionStorage | Supported | Not supported | Not supported | -| Encryption scope | Passwords, cookies, credit cards | Passwords only | Passwords only | -| Time format | WebKit microseconds since 1601 | Mixed (μs for most, ms for passwords) | Core Data seconds since 2001 | +| Aspect | Chromium | Firefox | Safari | +| --------------------------- | -------------------------------- | ------------------------------------- | --------------------------------------- | +| Platform | Cross-platform | Cross-platform | **macOS-only** | +| Profile discovery | `Preferences` sentinel file | Any data file present | `SafariTabs.db` SQL + dir fallback | +| Profile naming | `Default`, `Profile 1`, … | `.default-release` | Human-readable title from SafariTabs.db | +| Password storage | Encrypted SQLite (`Login Data`) | Encrypted JSON (`logins.json`) | **macOS Keychain** (no file) | +| Cookie encryption | Encrypted with OS master key | Plaintext | **Plaintext** | +| Cookie format | SQLite | SQLite | Proprietary BinaryCookies binary | +| History | SQLite | SQLite (`places.sqlite`) | SQLite (Core Data epoch) | +| Bookmark | JSON | SQLite (`places.sqlite`) | **plist** | +| Download | SQLite (`History`, shared) | SQLite (`places.sqlite`, shared) | **plist** (filtered by UUID) | +| LocalStorage | LevelDB | SQLite (`webappsstore.sqlite`) | Nested **WebKit Origins** SQLite | +| LocalStorage partitioning | No | No | **Yes** (top-frame + frame hashes) | +| CreditCard / SessionStorage | Supported | Not supported | Not supported | +| Encryption scope | Passwords, cookies, credit cards | Passwords only | Passwords only | +| Time format | WebKit microseconds since 1601 | Mixed (μs for most, ms for passwords) | Core Data seconds since 2001 | ## Related RFCs -| RFC | Topic | -|-----|-------| -| [RFC-001](001-project-architecture.md) | Project architecture and directory layout | -| [RFC-006](006-key-retrieval-mechanisms.md) | §7 covers Safari Keychain credential extraction | -| [RFC-008](008-file-acquisition-and-platform-quirks.md) | File acquisition via `filemanager.Session` | +| RFC | Topic | +| ------------------------------------------- | ----------------------------------------------- | +| [RFC-001](001-architecture-and-pipeline.md) | Architecture and pipeline | +| [RFC-015](015-key-retrieval-mechanisms.md) | §7 covers Safari Keychain credential extraction | +| [RFC-007](007-snapshot-and-acquisition.md) | Snapshot-first file acquisition | diff --git a/rfcs/009-windows-locked-file-bypass.md b/rfcs/021-windows-locked-file-bypass.md similarity index 85% rename from rfcs/009-windows-locked-file-bypass.md rename to rfcs/021-windows-locked-file-bypass.md index 29ca10c..dbc1f84 100644 --- a/rfcs/009-windows-locked-file-bypass.md +++ b/rfcs/021-windows-locked-file-bypass.md @@ -1,7 +1,7 @@ -# RFC-009: Windows Locked File Bypass +# RFC-021: Windows Locked File Bypass -**Author**: moonD4rk -**Status**: Living Document +**Author**: moonD4rk\ +**Status**: Living Document\ **Created**: 2026-04-05 ## 1. Problem @@ -41,13 +41,13 @@ The query starts with a 4 MB buffer and doubles it (up to 256 MB) if the API ret Each entry in the result table: -| Field | Size | Description | -|-------|------|-------------| -| Object | `uintptr` | Kernel object pointer | -| UniqueProcessID | `uintptr` | Owning process PID | -| HandleValue | `uintptr` | Handle value in the owning process | -| GrantedAccess | `uint32` | Access mask | -| ObjectTypeIndex | `uint16` | Kernel object type | +| Field | Size | Description | +| --------------- | --------- | ---------------------------------- | +| Object | `uintptr` | Kernel object pointer | +| UniqueProcessID | `uintptr` | Owning process PID | +| HandleValue | `uintptr` | Handle value in the owning process | +| GrantedAccess | `uint32` | Access mask | +| ObjectTypeIndex | `uint16` | Kernel object type | ### 3.2 Find the Target Handle @@ -116,6 +116,6 @@ This is a documented Windows behavior, not an exploit. The technique requires on ## Related RFCs -| RFC | Topic | -|-----|-------| -| [RFC-008](008-file-acquisition-and-platform-quirks.md) | File acquisition lifecycle and session management | +| RFC | Topic | +| ------------------------------------------ | ------------------------------- | +| [RFC-007](007-snapshot-and-acquisition.md) | Snapshot-first file acquisition | diff --git a/rfcs/README.md b/rfcs/README.md new file mode 100644 index 0000000..d195007 --- /dev/null +++ b/rfcs/README.md @@ -0,0 +1,63 @@ +# HackBrowserData RFCs + +This directory is HackBrowserData's design record. The design RFCs (000–012) describe how the program is organized — a single explicit pipeline, a flat `internal/` package tree, outcome-per-extraction reporting, and names that read the way Go wants them to read — while the tool's external interface stays exactly as it is in v1.1.0. The format and technique RFCs (013–021) describe how each browser stores and protects its data, and how the tool reads it. + +Every RFC states the current design. When a decision changes, the RFC is edited in place and git keeps the history; a superseded RFC is removed rather than kept beside its replacement. + +The design RFCs describe _architecture_ — how the program is organized, how data moves through it, what the packages and types are called, and which dependencies are chosen and why. They deliberately do **not** restate decryption algorithms, key-extraction techniques, or platform specifics. Those live in the format and technique RFCs and are referenced by boundary, not reproduced. + +## Why rewrite + +HackBrowserData is an MIT-licensed security-research tool with a large user base, presented at DEF CON. The rewrite serves three goals, in priority order: + +1. **A clean architecture that reads as a reference implementation.** The code is read on stage and by every contributor; it should teach the design, not apologize for it. +2. **A better operator experience without breaking anyone.** Fast failures, honest reporting, no surprises — and every existing command line, script, and output consumer keeps working unchanged. +3. **Durable code quality.** One obvious way to add a browser, a data type, or an output format — verified by tests, not tribal knowledge. + +## Hard constraints (non-negotiable) + +- **Go 1.20.** Windows 7 support depends on it. No Go 1.21+ features (`log/slog`, `slices`, `maps`, `cmp`, generic stdlib helpers that landed later), and no dependency version whose `go` directive is above 1.20. +- **Compatible external interface.** Commands, flags, defaults, output files and their field names, the `keys.json` and archive formats, and exit codes stay as they are in v1.1.0 — the compatibility contract in [RFC-000](000-goals-and-constraints.md). The rewrite lands as a series of PRs on an integration branch and reaches `main` in one fast-forward, on the existing module path; there is no v2 ([RFC-012](012-migration-roadmap.md)). +- **MIT license**, cross-platform (Windows, macOS, Linux), fully offline. The tool never phones home. +- **No new offensive capability.** The rewrite reorganizes and hardens existing, published functionality. It does not add targets, bypasses, or techniques. + +## Design + +| RFC | Title | What it settles | +| --------------------------------------- | ----------------------- | -------------------------------------------------------------------------- | +| [000](000-goals-and-constraints.md) | Goals & Constraints | Why we rewrite, the compatibility contract, guiding principles | +| [001](001-architecture-and-pipeline.md) | Architecture & Pipeline | The seven stages, data flow, outcome model, exit status | +| [002](002-package-layout.md) | Package Layout | The `internal/` tree, dependency direction, why `internal/` | +| [003](003-core-types.md) | Core Types | Every central type and its shape | +| [004](004-naming-decisions.md) | Naming Decisions | Settled names and the alternatives considered | +| [005](005-browser-definitions.md) | Browser Definitions | The supported-browser table, per-fork overrides, how a fork is added | +| [006](006-key-retrieval-and-crypto.md) | Key Retrieval & Crypto | `masterkey`, `crypto`, and `keychain` boundaries, key scopes, lazy secrets | +| [007](007-snapshot-and-acquisition.md) | Snapshot & Acquisition | Snapshot-first capture, user-data-dir identity, archive layout | +| [008](008-output-and-export.md) | Output & Export | Formats, frozen wire names, deterministic ordering | +| [009](009-cli-surface.md) | CLI Surface | The unchanged command surface, validation order, keychain password input | +| [010](010-dependencies.md) | Dependencies | Keep / drop / pin, with rationale | +| [011](011-testing-and-quality.md) | Testing & Quality | Test strategy, compatibility tests, CI, lint | +| [012](012-migration-roadmap.md) | Migration Roadmap | How the rewrite is delivered, phase by phase | + +## Formats and techniques + +| RFC | Title | What it covers | +| ---------------------------------------- | --------------------------------------- | ----------------------------------------------------------- | +| [013](013-chromium-data-storage.md) | Chromium Data Storage | Where Chromium keeps each category, and the file formats | +| [014](014-chromium-encryption.md) | Chromium Encryption | Cipher versions per platform | +| [015](015-key-retrieval-mechanisms.md) | Key Retrieval Mechanisms | Where each OS keeps the master key, and the Safari keychain | +| [016](016-chrome-abe-integration.md) | Chrome App-Bound Encryption Integration | The Windows `v20` key path and its payload | +| [017](017-yandex-decryption.md) | Yandex Browser Decryption | Yandex's own layer on top of Chromium's | +| [018](018-firefox-data-storage.md) | Firefox Data Storage | Where Firefox keeps each category, and the file formats | +| [019](019-firefox-encryption.md) | Firefox Encryption | The NSS key and login encryption | +| [020](020-safari-data-storage.md) | Safari Data Storage | Safari's files, profiles, and keychain passwords | +| [021](021-windows-locked-file-bypass.md) | Windows Locked File Bypass | Reading files a running browser keeps locked | + +## Status legend + +Each design RFC marks decisions as one of: + +- **DECIDED** — agreed; build to it. +- **DEFERRED** — intentionally left out of this rewrite; listed so it is not mistaken for an omission. + +Naming decisions and the alternatives behind them live in [004](004-naming-decisions.md).