diff --git a/cmd/hack-browser-data/archive.go b/cmd/hack-browser-data/archive.go index 59d3fb7..c8315aa 100644 --- a/cmd/hack-browser-data/archive.go +++ b/cmd/hack-browser-data/archive.go @@ -23,7 +23,7 @@ func newArchiveCommand() *cobra.Command { if err != nil { return err } - discovery := app.Discover(options.Target) + discovery := app.Discover(command.Context(), options.Target) if warnIfNothingFound(command.ErrOrStderr(), discovery, "no browsers found") { return nil } diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index 8f35943..03c5cda 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -45,7 +45,7 @@ func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychai if err != nil { return err } - discovery := app.Discover(options.Target) + discovery := app.Discover(ctx, options.Target) if warnIfNothingFound(stderr, discovery, "no browsers found") { return nil } diff --git a/cmd/hack-browser-data/dumpkeys.go b/cmd/hack-browser-data/dumpkeys.go index ad9718f..2173e7c 100644 --- a/cmd/hack-browser-data/dumpkeys.go +++ b/cmd/hack-browser-data/dumpkeys.go @@ -26,7 +26,7 @@ func newDumpKeysCommand() *cobra.Command { if err != nil { return err } - discovery := app.Discover(options.Target) + discovery := app.Discover(command.Context(), options.Target) vaultCount, err := app.DumpKeys(command.Context(), discovery, options.Keychain, command.OutOrStdout(), outputPath) if err != nil { return err diff --git a/cmd/hack-browser-data/list.go b/cmd/hack-browser-data/list.go index 10f14d2..c53b89d 100644 --- a/cmd/hack-browser-data/list.go +++ b/cmd/hack-browser-data/list.go @@ -20,7 +20,7 @@ func newListCommand() *cobra.Command { if err != nil { return err } - discovery := app.Discover(options.Target) + discovery := app.Discover(command.Context(), options.Target) for _, failure := range discovery.DirFailures { log.Warnf("%s: %v", failure.UserDataDirID, failure.Err) } diff --git a/internal/app/archive.go b/internal/app/archive.go index d495597..e0e6c6f 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -69,18 +69,17 @@ func Archive(ctx context.Context, discovery Discovery, categories []category.Cat } func archiveFiles(dirs []browser.UserDataDir, categories []category.Category) []snapshot.File { - extractors := extractorsWith(nil) var files []snapshot.File seen := make(map[snapshot.File]bool) for _, dir := range dirs { for _, profile := range dir.Profiles { for _, source := range chromium.ArchiveSources() { - if file, ok, err := firstOnDisk(dir, profile, source); err == nil && ok { + if file, ok, err := firstOnDisk(dir, source.CandidatePaths(profile), source.IsDir); err == nil && ok { files = appendNew(files, seen, file) } } } - files = appendNew(files, seen, planDir(dir, categories, extractors).files...) + files = appendNew(files, seen, planDir(dir, categories, extractorsFor).files...) } return files } diff --git a/internal/app/archive_golden_test.go b/internal/app/archive_golden_test.go index 8c8a754..c00197f 100644 --- a/internal/app/archive_golden_test.go +++ b/internal/app/archive_golden_test.go @@ -97,7 +97,7 @@ func TestArchiveGolden(t *testing.T) { require.NoError(t, err) options.Target.HomeDir = home out := filepath.Join(t.TempDir(), "browser-data.zip") - fileCount, err := app.Archive(context.Background(), app.Discover(options.Target), options.Categories, out) + fileCount, err := app.Archive(context.Background(), app.Discover(context.Background(), options.Target), options.Categories, out) require.NoError(t, err) golden.Assert(t, testCase.golden, fmt.Sprintf("entries=%d\n", fileCount)+golden.ZipListing(t, out)) diff --git a/internal/app/discover.go b/internal/app/discover.go index 0b8cb08..b3b1ca5 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -1,6 +1,7 @@ package app import ( + "context" "fmt" "github.com/moond4rk/hackbrowserdata/internal/browser" @@ -15,11 +16,11 @@ type Discovery struct { DirFailures []DirFailure } -func Discover(target Target) Discovery { +func Discover(ctx context.Context, target Target) Discovery { var discovery Discovery discoverOptions := browser.DiscoverOptions{HomeDir: target.HomeDir, ProfilePath: target.ProfilePath} for _, targetBrowser := range target.Browsers { - dirs, err := discover(targetBrowser, discoverOptions) + dirs, err := discover(ctx, targetBrowser, discoverOptions) discovery.Dirs = append(discovery.Dirs, withData(dirs)...) if err != nil { discovery.DirFailures = append(discovery.DirFailures, DirFailure{UserDataDirID: browser.UserDataDirID(targetBrowser.Name), Err: err}) @@ -30,12 +31,11 @@ func Discover(target Target) Discovery { // withData drops profiles holding no file any category reads, such as a bare Preferences, but keeps unreadable ones. func withData(dirs []browser.UserDataDir) []browser.UserDataDir { - extractors := extractorsWith(nil) var out []browser.UserDataDir for _, dir := range dirs { var profiles []browser.Profile for _, profile := range dir.Profiles { - if hasData(dir, profile, extractors(dir, profile)) { + if hasData(dir, profile, extractorsFor(dir, profile)) { profiles = append(profiles, profile) } } @@ -60,31 +60,29 @@ func hasData(dir browser.UserDataDir, profile browser.Profile, extractors browse } // discover dispatches on Base here, not in browser, because the base packages import browser. -func discover(supportedBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { - switch supportedBrowser.Base { +func discover(ctx context.Context, targetBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { + switch targetBrowser.Base { case browser.Chromium: - return chromium.Discover(supportedBrowser, options) + return chromium.Discover(targetBrowser, options) case browser.Firefox: - return firefox.Discover(supportedBrowser, options) + return firefox.Discover(targetBrowser, options) case browser.Safari: - return safari.Discover(supportedBrowser, options) + return safari.Discover(ctx, targetBrowser, options) default: - return nil, fmt.Errorf("%s: no base package", supportedBrowser.Name) + return nil, fmt.Errorf("%s: no base package", targetBrowser.Name) } } -// extractorsWith hands Safari the run's login keychain, which its default profile's password extractor reads. -func extractorsWith(keychain safari.LoginKeychain) extractorsFunc { - return func(dir browser.UserDataDir, profile browser.Profile) browser.Extractors { - switch dir.Browser.Base { - case browser.Chromium: - return chromium.Extractors(dir, profile) - case browser.Firefox: - return firefox.Extractors(dir, profile) - case browser.Safari: - return safari.Extractors(dir, profile, keychain) - default: - return nil - } +// extractorsFor dispatches on Base here for the same reason discover does. +func extractorsFor(dir browser.UserDataDir, profile browser.Profile) browser.Extractors { + switch dir.Browser.Base { + case browser.Chromium: + return chromium.Extractors(dir, profile) + case browser.Firefox: + return firefox.Extractors(dir, profile) + case browser.Safari: + return safari.Extractors(dir, profile) + default: + return nil } } diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index e318093..16e7fc5 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -1,6 +1,7 @@ package app import ( + "context" "os" "path/filepath" "runtime" @@ -35,11 +36,11 @@ func TestDiscover(t *testing.T) { writeUserDataDir(t, home, "edge") writeUserDataDir(t, home, "chrome") - discovery := Discover(Target{Browsers: browser.Supported(), HomeDir: home}) + discovery := Discover(context.Background(), Target{Browsers: browser.Supported(), HomeDir: home}) assert.Equal(t, []browser.UserDataDirID{"chrome", "edge"}, userDataDirIDs(discovery), "table order, which is output order") assert.Empty(t, discovery.DirFailures) - discovery = Discover(Target{Browsers: []browser.Browser{lookup(t, "edge")}, HomeDir: home}) + discovery = Discover(context.Background(), Target{Browsers: []browser.Browser{lookup(t, "edge")}, HomeDir: home}) assert.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery)) } @@ -50,7 +51,7 @@ func TestDiscover_ProfilePath(t *testing.T) { touch(t, custom, "Default", "Preferences") touch(t, custom, "Default", "History") - discovery := Discover(Target{Browsers: []browser.Browser{lookup(t, "chrome")}, HomeDir: home, ProfilePath: custom}) + discovery := Discover(context.Background(), Target{Browsers: []browser.Browser{lookup(t, "chrome")}, HomeDir: home, ProfilePath: custom}) require.Len(t, discovery.Dirs, 1) assert.Equal(t, custom, discovery.Dirs[0].Path) } @@ -63,7 +64,7 @@ func TestDiscover_KeepsOnlyProfilesWithData(t *testing.T) { edge := writeUserDataDir(t, home, "edge") require.NoError(t, os.Remove(filepath.Join(edge, "Default", "History"))) - discovery := Discover(Target{Browsers: browser.Supported(), HomeDir: home}) + discovery := Discover(context.Background(), Target{Browsers: browser.Supported(), HomeDir: home}) assert.Equal(t, []browser.UserDataDirID{"chrome"}, userDataDirIDs(discovery)) assert.Equal(t, []browser.Profile{{Name: "Default", RelativePath: "Default"}}, discovery.Dirs[0].Profiles) } @@ -77,7 +78,7 @@ func TestDiscover_UnreadableDirIsReported(t *testing.T) { require.NoError(t, os.Chmod(path, 0o000)) defer func() { require.NoError(t, os.Chmod(path, 0o700)) }() - discovery := Discover(Target{Browsers: browser.Supported(), HomeDir: home}) + discovery := Discover(context.Background(), Target{Browsers: browser.Supported(), HomeDir: home}) assert.Empty(t, discovery.Dirs) require.Len(t, discovery.DirFailures, 1) assert.Equal(t, browser.UserDataDirID("chrome"), discovery.DirFailures[0].UserDataDirID) diff --git a/internal/app/dumpkeys.go b/internal/app/dumpkeys.go index 261971f..200ad3e 100644 --- a/internal/app/dumpkeys.go +++ b/internal/app/dumpkeys.go @@ -107,7 +107,7 @@ func retrieveDirKeys(ctx context.Context, dir browser.UserDataDir, keys dirKeysF defer closeRoot(root) var files []snapshot.File for _, source := range chromium.KeySources() { - if file, ok, err := firstOnDisk(dir, browser.Profile{}, source); err == nil && ok { + if file, ok, err := firstOnDisk(dir, source.Paths(), source.IsDir); err == nil && ok { files = append(files, file) } } diff --git a/internal/app/execute.go b/internal/app/execute.go index bf5c3b1..b86d0db 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -21,24 +21,25 @@ func Execute( ctx context.Context, discovery Discovery, categories []category.Category, output Output, keychainConfig KeychainConfig, ) (Summary, error) { keychain := newLoginKeychain(keychainConfig) - return execute(ctx, discovery, categories, output, extractorsWith(keychain), keysFromMachine(keychain)) + fromMachine := runner{extractors: extractorsFor, retrieveKeys: keysFromMachine(keychain), loginKeychain: keychain} + return execute(ctx, discovery, categories, output, fromMachine) } // ExecuteWithKeys decrypts with a key file's keys, so it never reads this machine's secret stores. func ExecuteWithKeys( ctx context.Context, discovery Discovery, categories []category.Category, output Output, keys map[browser.UserDataDirID]masterkey.Set, ) (Summary, error) { - return execute(ctx, discovery, categories, output, extractorsWith(nil), keysFromFile(keys)) + return execute(ctx, discovery, categories, output, runner{extractors: extractorsFor, retrieveKeys: keysFromFile(keys)}) } -func execute( - ctx context.Context, discovery Discovery, categories []category.Category, output Output, extractors extractorsFunc, keys dirKeysFunc, -) (Summary, error) { +// execute gives the runner the run's writer; the caller sets where its extractors, keys, and keychain come from. +func execute(ctx context.Context, discovery Discovery, categories []category.Category, output Output, dirRunner runner) (Summary, error) { writer, err := export.NewWriter(output.Dir, output.Format, output.Zip) if err != nil { return Summary{}, err } - summary, err := runner{writer: writer, extractors: extractors, retrieveKeys: keys, logProgress: true}.run(ctx, discovery, categories) + dirRunner.writer, dirRunner.logProgress = writer, true + summary, err := dirRunner.run(ctx, discovery, categories) closeErr := writer.Close() summary.Exported = writer.Listing() return summary, errors.Join(err, closeErr) @@ -50,10 +51,11 @@ type recordWriter interface { // runner is what every user data dir of one run shares; logProgress logs each dir as it starts. type runner struct { - writer recordWriter - extractors extractorsFunc - retrieveKeys dirKeysFunc - logProgress bool + writer recordWriter + extractors extractorsFunc + retrieveKeys dirKeysFunc + loginKeychain browser.LoginKeychain + logProgress bool } func (r runner) run(ctx context.Context, discovery Discovery, categories []category.Category) (Summary, error) { @@ -105,8 +107,8 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories if err := ctx.Err(); err != nil { return summary, fmt.Errorf("run stopped: %w", err) } - profileSnapshot := browser.NewProfileSnapshot(dirSnapshot, extraction.profile, keys.get) - result, err := r.runExtraction(ctx, extraction, profileSnapshot, dir.Browser.DisplayName) + input := browser.NewInput(dirSnapshot, extraction.profile, keys.get, r.loginKeychain) + result, err := r.runExtraction(ctx, extraction, input, dir.Browser.DisplayName) if err != nil { return summary, err } @@ -121,10 +123,10 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories // runExtraction exports the records emitted before an extraction failed, as they always were; its error stops the run. func (r runner) runExtraction( - ctx context.Context, extraction plannedExtraction, profileSnapshot browser.ProfileSnapshot, browserName string, + ctx context.Context, extraction plannedExtraction, input browser.Input, browserName string, ) (Result, error) { recordCollector := &collector{browserName: browserName, profileName: extraction.ProfileName} - err := extraction.extractor.Extract(ctx, profileSnapshot, recordCollector) + err := extraction.extractor.Extract(ctx, input, recordCollector) if writeErr := r.writer.Write(extraction.Category, recordCollector.records); writeErr != nil { return Result{}, writeErr } diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go index 4454a97..733bf50 100644 --- a/internal/app/execute_test.go +++ b/internal/app/execute_test.go @@ -22,7 +22,7 @@ import ( var history = browser.Source{Path: "History"} -type extractFunc func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error +type extractFunc func(ctx context.Context, input browser.Input, out browser.Collector) error // fakeBase reads History for every category, so a test needs one fixture file per profile. func fakeBase(extractFuncs map[category.Category]extractFunc) extractorsFunc { @@ -55,7 +55,7 @@ func chromeDir(t *testing.T, id browser.UserDataDirID, profiles ...string) brows func run(t *testing.T, base extractorsFunc, keys dirKeysFunc, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) { t.Helper() output := Output{Dir: t.TempDir()} - summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, base, keys) + summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, runner{extractors: base, retrieveKeys: keys}) require.NoError(t, err) return summary, output.Dir } @@ -71,28 +71,28 @@ func outcomes(summary Summary) map[category.Category]Result { func TestExecute_Outcomes(t *testing.T) { cookie := func(name string) *record.Cookie { return &record.Cookie{Name: name} } base := fakeBase(map[category.Category]extractFunc{ - category.Cookie: func(_ context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { + category.Cookie: func(_ context.Context, _ browser.Input, out browser.Collector) error { out.Add(cookie("a")) out.Add(cookie("b")) out.Fail(errors.New("value not decrypted")) return nil }, - category.Password: func(_ context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { + category.Password: func(_ context.Context, _ browser.Input, out browser.Collector) error { out.Fail(errors.New("password not decrypted")) return nil }, - category.History: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { return nil }, - category.Bookmark: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { + category.History: func(context.Context, browser.Input, browser.Collector) error { return nil }, + category.Bookmark: func(context.Context, browser.Input, browser.Collector) error { return errors.New("corrupt") }, - category.Download: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { + category.Download: func(context.Context, browser.Input, browser.Collector) error { return fmt.Errorf("History: %w", fs.ErrNotExist) }, - category.Extension: func(_ context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { + category.Extension: func(_ context.Context, _ browser.Input, out browser.Collector) error { out.Add(&record.Extension{Name: "kept"}) return errors.New("truncated") }, - category.CreditCard: func(_ context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { + category.CreditCard: func(_ context.Context, _ browser.Input, out browser.Collector) error { out.Add(&record.CreditCard{Name: "kept"}) return fmt.Errorf("Web Data: %w", fs.ErrNotExist) }, @@ -129,12 +129,12 @@ func TestExecute_ReportsEachDirWhatNeverRanFirst(t *testing.T) { failed := DirFailure{UserDataDirID: "edge", Err: errors.New("permission denied")} chrome, brave := chromeDir(t, "chrome", "Default"), chromeDir(t, "brave", "Default") base := fakeBase(map[category.Category]extractFunc{ - category.History: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { return nil }, + category.History: func(context.Context, browser.Input, browser.Collector) error { return nil }, }) categories := []category.Category{category.Password, category.History} discovery := Discovery{Dirs: []browser.UserDataDir{chrome, brave}, DirFailures: []DirFailure{failed}} - summary, err := execute(context.Background(), discovery, categories, Output{Dir: t.TempDir()}, base, noKeys(t)) + summary, err := execute(context.Background(), discovery, categories, Output{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: noKeys(t)}) require.NoError(t, err) assert.Equal(t, []DirFailure{failed}, summary.DirFailures, "discovery's failures are reported with the run's") var got []string @@ -148,12 +148,12 @@ func TestExecute_ReportsEachDirWhatNeverRanFirst(t *testing.T) { } func TestExecute_KeysAreRetrievedOncePerUserDataDir(t *testing.T) { - cookie := func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { - out.Add(&record.Cookie{Value: string(profileSnapshot.MasterKeys(ctx)[masterkey.V10])}) + cookie := func(ctx context.Context, input browser.Input, out browser.Collector) error { + out.Add(&record.Cookie{Value: string(input.MasterKeys(ctx)[masterkey.V10])}) return nil } - login := func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { - out.Add(&record.Login{Password: string(profileSnapshot.MasterKeys(ctx)[masterkey.V10])}) + login := func(ctx context.Context, input browser.Input, out browser.Collector) error { + out.Add(&record.Login{Password: string(input.MasterKeys(ctx)[masterkey.V10])}) return nil } calls := 0 @@ -185,18 +185,18 @@ func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) { touch(t, path, "Default", "History") dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}} - run(t, extractorsWith(nil), noKeys(t), []category.Category{category.History, category.Download}, dir) + run(t, extractorsFor, noKeys(t), []category.Category{category.History, category.Download}, dir) } func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) { var captured []string base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, _ browser.Collector) error { + category.History: func(_ context.Context, input browser.Input, _ browser.Collector) error { for _, earlier := range captured { _, err := os.Stat(earlier) require.ErrorIs(t, err, fs.ErrNotExist, "an earlier dir's copy is still on disk") } - path, err := profileSnapshot.Path(history) + path, err := input.Path(history) require.NoError(t, err) captured = append(captured, path) return nil @@ -216,14 +216,14 @@ func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testi defer cancel() var copied []string base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, _ browser.Collector) error { - path, err := profileSnapshot.Path(history) + category.History: func(_ context.Context, input browser.Input, _ browser.Collector) error { + path, err := input.Path(history) require.NoError(t, err) copied = append(copied, path) cancel() return nil }, - category.Download: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { + category.Download: func(context.Context, browser.Input, browser.Collector) error { t.Error("an extraction ran after the stop") return nil }, @@ -231,7 +231,7 @@ func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testi categories := []category.Category{category.History, category.Download} discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")}} - _, err := execute(ctx, discovery, categories, Output{Dir: t.TempDir()}, base, noKeys(t)) + _, err := execute(ctx, discovery, categories, Output{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: noKeys(t)}) require.ErrorIs(t, err, context.Canceled) require.Len(t, copied, 1, "the next user data dir is never captured") _, statErr := os.Stat(copied[0]) @@ -244,14 +244,14 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { } var copied string base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + category.History: func(_ context.Context, input browser.Input, out browser.Collector) error { var err error - copied, err = profileSnapshot.Path(history) + copied, err = input.Path(history) require.NoError(t, err) out.Add(&record.History{URL: "https://example.com"}) return nil }, - category.Download: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { + category.Download: func(context.Context, browser.Input, browser.Collector) error { t.Error("an extraction ran after the output failed") return nil }, @@ -261,7 +261,7 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { defer func() { require.NoError(t, os.Chmod(output.Dir, 0o700)) }() discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}} - _, err := execute(context.Background(), discovery, []category.Category{category.History, category.Download}, output, base, noKeys(t)) + _, err := execute(context.Background(), discovery, []category.Category{category.History, category.Download}, output, runner{extractors: base, retrieveKeys: noKeys(t)}) require.Error(t, err) require.NotEmpty(t, copied) _, statErr := os.Stat(copied) diff --git a/internal/app/extract_golden_test.go b/internal/app/extract_golden_test.go index b1eb7fe..9b75621 100644 --- a/internal/app/extract_golden_test.go +++ b/internal/app/extract_golden_test.go @@ -63,7 +63,7 @@ func extractGoldenRun(t *testing.T, home string, keys map[browser.UserDataDirID] require.NoError(t, err) options.Target.HomeDir = home - _, err = app.ExecuteWithKeys(context.Background(), app.Discover(options.Target), options.Categories, options.Output, keys) + _, err = app.ExecuteWithKeys(context.Background(), app.Discover(context.Background(), options.Target), options.Categories, options.Output, keys) require.NoError(t, err) return out } diff --git a/internal/app/keychain_darwin.go b/internal/app/keychain_darwin.go index 1e98264..a9b534b 100644 --- a/internal/app/keychain_darwin.go +++ b/internal/app/keychain_darwin.go @@ -7,8 +7,6 @@ import ( "path/filepath" "sync" - "github.com/moond4rk/keychainbreaker" - "github.com/moond4rk/hackbrowserdata/internal/keychain" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -37,7 +35,7 @@ func (k *reportingKeychain) GenericPassword(ctx context.Context, account string) return secret, err } -func (k *reportingKeychain) InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) { +func (k *reportingKeychain) InternetPasswords(ctx context.Context) ([]keychain.InternetPassword, error) { passwords, err := k.Keychain.InternetPasswords(ctx) k.warnLockedOnce() return passwords, err diff --git a/internal/app/list.go b/internal/app/list.go index 14a0505..414d35e 100644 --- a/internal/app/list.go +++ b/internal/app/list.go @@ -28,7 +28,7 @@ func ValidateList() (ListOptions, error) { // CountRecords runs every category with no key and the keychain locked, counting records instead of exporting them. func CountRecords(ctx context.Context, discovery Discovery, keychainConfig KeychainConfig) (Summary, error) { keychain := newLoginKeychain(keychainConfig) - counter := runner{writer: discard{}, extractors: extractorsWith(keychain), retrieveKeys: keysFromFile(nil)} + counter := runner{writer: discard{}, extractors: extractorsFor, retrieveKeys: keysFromFile(nil), loginKeychain: keychain} return counter.run(ctx, discovery, category.All()) } diff --git a/internal/app/masterkeys.go b/internal/app/masterkeys.go index a5038d9..6dcecdb 100644 --- a/internal/app/masterkeys.go +++ b/internal/app/masterkeys.go @@ -6,7 +6,6 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" - "github.com/moond4rk/hackbrowserdata/internal/browser/safari" "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) @@ -14,7 +13,7 @@ import ( // loginKeychain is the run's one login keychain, shared by Chromium's v10 key and Safari's passwords; nil off macOS. type loginKeychain interface { masterkey.LoginKeychain - safari.LoginKeychain + browser.LoginKeychain } type dirKeysFunc func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) diff --git a/internal/app/plan.go b/internal/app/plan.go index 4b3fda1..d71e3c9 100644 --- a/internal/app/plan.go +++ b/internal/app/plan.go @@ -71,7 +71,7 @@ func locate(dir browser.UserDataDir, profile browser.Profile, sources []browser. return nil, true, nil } for _, source := range sources { - file, ok, err := firstOnDisk(dir, profile, source) + file, ok, err := firstOnDisk(dir, source.CandidatePaths(profile), source.IsDir) switch { case err != nil: return nil, false, err @@ -85,13 +85,14 @@ func locate(dir browser.UserDataDir, profile browser.Profile, sources []browser. return files, present, nil } -func firstOnDisk(dir browser.UserDataDir, profile browser.Profile, source browser.Source) (snapshot.File, bool, error) { - for _, relativePath := range source.CandidatePaths(profile) { +// firstOnDisk takes relativePaths under the dir, in the order a source tries them. +func firstOnDisk(dir browser.UserDataDir, relativePaths []string, isDir bool) (snapshot.File, bool, error) { + for _, relativePath := range relativePaths { info, err := os.Stat(filepath.Join(dir.Path, filepath.FromSlash(relativePath))) switch { - case err == nil && info.IsDir() == source.IsDir: + case err == nil && info.IsDir() == isDir: return snapshot.File{ - UserDataDirID: string(dir.ID), UserDataDirPath: dir.Path, RelativePath: relativePath, IsDir: source.IsDir, + UserDataDirID: string(dir.ID), UserDataDirPath: dir.Path, RelativePath: relativePath, IsDir: isDir, }, true, nil case err != nil && !errors.Is(err, fs.ErrNotExist): return snapshot.File{}, false, err diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index 418375b..1d6d4fb 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -50,7 +50,7 @@ func TestPlanDir(t *testing.T) { } categories := []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard} - plan := planDir(dir, categories, extractorsWith(nil)) + plan := planDir(dir, categories, extractorsFor) file := func(relativePath string) snapshot.File { return snapshot.File{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: relativePath} @@ -85,11 +85,11 @@ func TestPlanDir_PicksTheFirstCandidateOnDisk(t *testing.T) { touch(t, path, "Default", "Cookies") dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}} - plan := planDir(dir, []category.Category{category.Cookie}, extractorsWith(nil)) + plan := planDir(dir, []category.Category{category.Cookie}, extractorsFor) assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Cookies"}}, plan.files) touch(t, path, "Default", "Network", "Cookies") - plan = planDir(dir, []category.Category{category.Cookie}, extractorsWith(nil)) + plan = planDir(dir, []category.Category{category.Cookie}, extractorsFor) assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Network/Cookies"}}, plan.files, "a leftover legacy Cookies never wins") } @@ -99,7 +99,7 @@ func TestPlanDir_FlatLayoutProfile(t *testing.T) { touch(t, path, "History") dir := browser.UserDataDir{ID: "opera", Browser: lookup(t, "opera"), Path: path, Profiles: []browser.Profile{{Name: "Opera Stable"}}} - plan := planDir(dir, []category.Category{category.History}, extractorsWith(nil)) + plan := planDir(dir, []category.Category{category.History}, extractorsFor) assert.Equal(t, []snapshot.File{{UserDataDirID: "opera", UserDataDirPath: path, RelativePath: "History"}}, plan.files) assert.Equal(t, []Extraction{{UserDataDirID: "opera", ProfileName: "Opera Stable", Category: category.History}}, extractionsOf(plan)) } diff --git a/internal/app/restore.go b/internal/app/restore.go index da24c48..6bdcb36 100644 --- a/internal/app/restore.go +++ b/internal/app/restore.go @@ -163,14 +163,11 @@ func DiscoverRestore(root string, vaults []masterkey.Vault) (Discovery, map[brow } func restoredDir(vault masterkey.Vault, id browser.UserDataDirID, path string) (browser.UserDataDir, error) { - restoredBrowser, err := vaultBrowser(vault) + restoredBrowser, vaultKind := vaultBrowser(vault) + dir, err := chromium.DiscoverAt(restoredBrowser, vaultKind, id, path) if err != nil { return browser.UserDataDir{}, err } - dir, err := chromium.DiscoverAt(restoredBrowser, id, path) - if err != nil { - return browser.UserDataDir{}, fmt.Errorf("read %s: %w", path, err) - } found := withData([]browser.UserDataDir{dir}) if len(found) == 0 { return browser.UserDataDir{}, fmt.Errorf("found no profiles under %s", path) @@ -179,17 +176,13 @@ func restoredDir(vault masterkey.Vault, id browser.UserDataDirID, path string) ( } // vaultBrowser searches the whole table, so a fork this OS lacks still restores. A browser this build does not know -// restores as it always did: the vault's kind picks the on-disk format, and its name stands in as the browser. -func vaultBrowser(vault masterkey.Vault) (browser.Browser, error) { +// keeps its own name, and its vault's kind picks the on-disk format. +func vaultBrowser(vault masterkey.Vault) (restored browser.Browser, vaultKind string) { name := strings.ToLower(vault.Browser) if namedBrowser, ok := browser.Lookup(name); ok && namedBrowser.Base == browser.Chromium { - return namedBrowser, nil + return namedBrowser, chromium.VaultKind(namedBrowser) } - formatName, err := chromium.BrowserNameForKind(vault.Kind, name) - if err != nil { - return browser.Browser{}, err - } - return browser.Browser{Name: formatName, DisplayName: vault.Browser, Base: browser.Chromium}, nil + return browser.Browser{Name: name, DisplayName: vault.Browser, Base: browser.Chromium}, vault.Kind } // vaultUserDataDirID is the vault's directory in an archive: its ID for a second user data dir, else its browser name. diff --git a/internal/app/restore_golden_test.go b/internal/app/restore_golden_test.go index b9d651e..4fed706 100644 --- a/internal/app/restore_golden_test.go +++ b/internal/app/restore_golden_test.go @@ -71,7 +71,7 @@ func TestArchiveRestoreRoundTrip(t *testing.T) { require.NoError(t, err) options.Target.HomeDir = home archive := filepath.Join(t.TempDir(), "data.zip") - _, err = app.Archive(context.Background(), app.Discover(options.Target), options.Categories, archive) + _, err = app.Archive(context.Background(), app.Discover(context.Background(), options.Target), options.Categories, archive) require.NoError(t, err) out := restoreGolden(t, app.RestoreFlags{KeyFile: chromiumKeyFile(t), DataZip: archive, OutputDir: t.TempDir()}) diff --git a/internal/app/restore_test.go b/internal/app/restore_test.go index 18f051e..8a16a21 100644 --- a/internal/app/restore_test.go +++ b/internal/app/restore_test.go @@ -95,8 +95,9 @@ func TestDiscoverRestore_FromLayout(t *testing.T) { require.NoError(t, err) assert.Equal(t, []browser.UserDataDirID{"chrome", "nightly"}, userDataDirIDs(discovery), "a repeated vault restores once, one without data not at all") assert.Len(t, keys, 2) - assert.Equal(t, browser.Browser{Name: "yandex", DisplayName: "Nightly", Base: browser.Chromium}, discovery.Dirs[1].Browser, - "a key this build does not know keeps its kind's format and its own name") + assert.Equal(t, browser.Browser{Name: "nightly", DisplayName: "Nightly", Base: browser.Chromium}, discovery.Dirs[1].Browser, + "a browser this build does not know keeps its own name") + assert.Equal(t, "chromium-yandex", discovery.Dirs[1].VaultKind, "and its vault's kind picks the format") } func TestDiscoverRestore_OneUserDataNeedsOneVault(t *testing.T) { diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index d5c9ff5..56237e9 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -40,12 +40,16 @@ func Discover(chromiumBrowser browser.Browser, options browser.DiscoverOptions) return dirs, errors.Join(errs...) } -// DiscoverAt reads the profiles of a user data dir the table does not name, such as a copy restore was given. -func DiscoverAt(chromiumBrowser browser.Browser, id browser.UserDataDirID, path string) (browser.UserDataDir, error) { - dir := browser.UserDataDir{ID: id, Browser: chromiumBrowser, Path: path} +// DiscoverAt reads the profiles of a user data dir the table does not name, such as a copy restore was given, in the +// on-disk format vaultKind names. +func DiscoverAt(chromiumBrowser browser.Browser, vaultKind string, id browser.UserDataDirID, path string) (browser.UserDataDir, error) { + if !isVaultKind(vaultKind) { + return browser.UserDataDir{}, fmt.Errorf("unknown vault kind %q", vaultKind) + } + dir := browser.UserDataDir{ID: id, Browser: chromiumBrowser, Path: path, VaultKind: vaultKind} profiles, err := discoverProfiles(dir) if err != nil { - return dir, err + return dir, fmt.Errorf("read %s: %w", path, err) } dir.Profiles = profiles return dir, nil @@ -136,7 +140,7 @@ func isSkippedProfileDir(name string) bool { func profileFilePaths(dir browser.UserDataDir) []string { var paths []string - for _, extractor := range Extractors(dir, browser.Profile{}) { + for _, extractor := range kindExtractors(vaultKindOf(dir)) { for _, source := range extractor.Sources { if !source.Shared { paths = append(paths, source.Paths()...) diff --git a/internal/browser/chromium/extractors.go b/internal/browser/chromium/extractors.go index d37273d..dc89bb9 100644 --- a/internal/browser/chromium/extractors.go +++ b/internal/browser/chromium/extractors.go @@ -38,11 +38,15 @@ var defaultExtractors = browser.Extractors{ } func Extractors(dir browser.UserDataDir, _ browser.Profile) browser.Extractors { + return kindExtractors(vaultKindOf(dir)) +} + +func kindExtractors(vaultKind string) browser.Extractors { extractors := make(browser.Extractors, len(defaultExtractors)) for dataCategory, extractor := range defaultExtractors { extractors[dataCategory] = extractor } - if fork, ok := overrideFor(dir.Browser.Name); ok { + if fork, ok := overrideForVaultKind(vaultKind); ok { for dataCategory, extractor := range fork.extractors { extractors[dataCategory] = extractor } @@ -55,15 +59,15 @@ func newDecryptingExtractor(parse func(masterKeysFunc, string, browser.Collector return browser.Extractor{ // The dir's master keys come from KeySources, so a decrypting extraction must find them in the snapshot too. Sources: append(sources, KeySources()...), - Extract: func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + Extract: func(ctx context.Context, input browser.Input, out browser.Collector) error { var errs []error for _, source := range sources { - path, err := profileSnapshot.Path(source) + path, err := input.Path(source) if source.Optional && errors.Is(err, fs.ErrNotExist) { continue } if err == nil { - err = parse(masterKeysOf(ctx, profileSnapshot), path, out) + err = parse(masterKeysOf(ctx, input), path, out) } errs = append(errs, err) } @@ -72,15 +76,15 @@ func newDecryptingExtractor(parse func(masterKeysFunc, string, browser.Collector } } -func masterKeysOf(ctx context.Context, profileSnapshot browser.ProfileSnapshot) masterKeysFunc { - return func() masterkey.Set { return profileSnapshot.MasterKeys(ctx) } +func masterKeysOf(ctx context.Context, input browser.Input) masterKeysFunc { + return func() masterkey.Set { return input.MasterKeys(ctx) } } func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor { return browser.Extractor{ Sources: []browser.Source{source}, - Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { - path, err := profileSnapshot.Path(source) + Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { + path, err := input.Path(source) if err != nil { return err } diff --git a/internal/browser/chromium/extractors_test.go b/internal/browser/chromium/extractors_test.go index dddddf3..d21b393 100644 --- a/internal/browser/chromium/extractors_test.go +++ b/internal/browser/chromium/extractors_test.go @@ -41,7 +41,7 @@ func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) { want := map[string]string{"Default": "Home", "Profile 1": "Work"} for _, profile := range []browser.Profile{{Name: "Default", RelativePath: "Default"}, {Name: "Profile 1", RelativePath: "Profile 1"}} { var out testCollector - require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewProfileSnapshot(dirSnapshot, profile, nil), &out)) + require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, nil), &out)) got := collected[record.History](t, &out) require.Len(t, got, 1, profile.Name) assert.Equal(t, want[profile.Name], got[0].Title, profile.Name) @@ -52,13 +52,13 @@ func TestDecryptingExtractor_ReadsSourcesInOrder(t *testing.T) { local := createTestDB(t, "Login Data", loginsSchema, insertLogin("https://local.example", "", "local-user", "", 13340000000000000)) account := createTestDB(t, "Login Data For Account", loginsSchema, insertLogin("https://account.example", "", "account-user", "", 13360000000000000)) - profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ + input := browser.NewInput(snapshotOf(t, map[string]string{ "Default/Login Data": local, "Default/Login Data For Account": account, - }), browser.Profile{Name: "Default", RelativePath: "Default"}, nil) + }), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), profileSnapshot, &out)) + require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 2) assert.Equal(t, "local-user", got[0].Username) @@ -70,11 +70,11 @@ func TestDecryptingExtractor_ReadsSourcesInOrder(t *testing.T) { func TestDecryptingExtractor_SkipsAbsentOptionalSource(t *testing.T) { account := createTestDB(t, "Login Data For Account", loginsSchema, insertLogin("https://account.example", "", "account-user", "", 13360000000000000)) - profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"Default/Login Data For Account": account}), - browser.Profile{Name: "Default", RelativePath: "Default"}, nil) + input := browser.NewInput(snapshotOf(t, map[string]string{"Default/Login Data For Account": account}), + browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), profileSnapshot, &out)) + require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 1) assert.Equal(t, record.StoreAccount, got[0].Store) @@ -84,12 +84,12 @@ func TestDecryptingExtractor_BrokenSourceKeepsTheOthers(t *testing.T) { broken := createTestJSON(t, "Login Data", "not a database") account := createTestDB(t, "Login Data For Account", loginsSchema, insertLogin("https://account.example", "", "account-user", "", 13360000000000000)) - profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ + input := browser.NewInput(snapshotOf(t, map[string]string{ "Default/Login Data": broken, "Default/Login Data For Account": account, - }), browser.Profile{Name: "Default", RelativePath: "Default"}, nil) + }), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) var out testCollector - require.Error(t, defaultExtractors[category.Password].Extract(context.Background(), profileSnapshot, &out)) + require.Error(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) assert.Len(t, collected[record.Login](t, &out), 1) } diff --git a/internal/browser/chromium/override.go b/internal/browser/chromium/override.go index 164b737..e661643 100644 --- a/internal/browser/chromium/override.go +++ b/internal/browser/chromium/override.go @@ -1,8 +1,6 @@ package chromium import ( - "fmt" - "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/category" ) @@ -47,6 +45,20 @@ func overrideFor(browserName string) (override, bool) { return override{}, false } +func overrideForVaultKind(vaultKind string) (override, bool) { + for _, fork := range overrides { + if fork.vaultKind == vaultKind { + return fork, true + } + } + return override{}, false +} + +func isVaultKind(vaultKind string) bool { + _, ok := overrideForVaultKind(vaultKind) + return ok || vaultKind == vaultKindChromium +} + // VaultKind names a vault's on-disk format, so a reader without the browser in its table still picks its files. func VaultKind(chromiumBrowser browser.Browser) string { if fork, ok := overrideFor(chromiumBrowser.Name); ok { @@ -55,15 +67,10 @@ func VaultKind(chromiumBrowser browser.Browser) string { return vaultKindChromium } -// BrowserNameForKind names the browser whose extractors read a vault of kind; a plain Chromium vault keeps its own. -func BrowserNameForKind(kind, name string) (string, error) { - if kind == vaultKindChromium { - return name, nil +// vaultKindOf is a restored dir's own kind, or else its browser's. +func vaultKindOf(dir browser.UserDataDir) string { + if dir.VaultKind != "" { + return dir.VaultKind } - for _, fork := range overrides { - if fork.vaultKind == kind { - return fork.browserNames[0], nil - } - } - return "", fmt.Errorf("unknown vault kind %q", kind) + return VaultKind(dir.Browser) } diff --git a/internal/browser/chromium/override_test.go b/internal/browser/chromium/override_test.go index 6fb7242..96e1eb9 100644 --- a/internal/browser/chromium/override_test.go +++ b/internal/browser/chromium/override_test.go @@ -23,7 +23,7 @@ func TestOverrides_NameChromiumBrowsers(t *testing.T) { } } -// TestOverrides_KindsAndNamesAreUnique keeps BrowserNameForKind and overrideFor from depending on table order. +// TestOverrides_KindsAndNamesAreUnique keeps overrideFor and overrideForVaultKind from depending on table order. func TestOverrides_KindsAndNamesAreUnique(t *testing.T) { kinds := map[string]bool{vaultKindChromium: true} names := map[string]bool{} @@ -43,19 +43,27 @@ func TestVaultKind_RoundTripsEveryFork(t *testing.T) { for _, name := range fork.browserNames { kind := VaultKind(browser.Browser{Name: name}) require.Equalf(t, fork.vaultKind, kind, "override %q", name) - forkBrowserName, err := BrowserNameForKind(kind, "unknown") - require.NoError(t, err) - restored, ok := overrideFor(forkBrowserName) - require.True(t, ok, forkBrowserName) + restored, ok := overrideForVaultKind(kind) + require.True(t, ok, kind) assert.Equalf(t, categoriesOf(fork.extractors), categoriesOf(restored.extractors), "kind %s of %q", kind, name) } } assert.Equal(t, vaultKindChromium, VaultKind(browser.Browser{Name: "chrome"})) - plainBrowserName, err := BrowserNameForKind(vaultKindChromium, "unknown") + assert.True(t, isVaultKind(vaultKindChromium)) + assert.False(t, isVaultKind("bogus")) + assert.False(t, isVaultKind("")) +} + +// TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind keeps a restored fork's own name while its kind picks the files. +func TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind(t *testing.T) { + nightly := browser.Browser{Name: "nightly", DisplayName: "Nightly", Base: browser.Chromium} + dir, err := DiscoverAt(nightly, "chromium-yandex", "nightly", t.TempDir()) require.NoError(t, err) - assert.Equal(t, "unknown", plainBrowserName) - _, err = BrowserNameForKind("bogus", "unknown") - assert.Error(t, err) + assert.Equal(t, nightly, dir.Browser) + assert.Equal(t, "Ya Passman Data", Extractors(dir, browser.Profile{})[category.Password].Sources[0].Path) + + _, err = DiscoverAt(nightly, "bogus", "nightly", t.TempDir()) + require.Error(t, err) } func categoriesOf(extractors browser.Extractors) []category.Category { @@ -72,14 +80,14 @@ func TestExtractors_OperaReadsOpsettings(t *testing.T) { preferencesPath := createTestJSON(t, "Secure Preferences", `{ "extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Opera Ext", "version": "1.0"}}}} }`) - profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"Default/Secure Preferences": preferencesPath}), - browser.Profile{Name: "Default", RelativePath: "Default"}, nil) + input := browser.NewInput(snapshotOf(t, map[string]string{"Default/Secure Preferences": preferencesPath}), + browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) for _, name := range []string{"opera", "opera-gx", "vought"} { chromiumBrowser, ok := browser.Lookup(name) require.True(t, ok, name) var out testCollector - require.NoError(t, Extractors(browser.UserDataDir{Browser: chromiumBrowser}, profileSnapshot.Profile)[category.Extension].Extract(context.Background(), profileSnapshot, &out), name) + require.NoError(t, Extractors(browser.UserDataDir{Browser: chromiumBrowser}, input.Profile)[category.Extension].Extract(context.Background(), input, &out), name) got := collected[record.Extension](t, &out) require.Len(t, got, 1, name) assert.Equal(t, "Opera Ext", got[0].Name, name) @@ -87,6 +95,6 @@ func TestExtractors_OperaReadsOpsettings(t *testing.T) { chrome, ok := browser.Lookup("chrome") require.True(t, ok) - err := Extractors(browser.UserDataDir{Browser: chrome}, profileSnapshot.Profile)[category.Extension].Extract(context.Background(), profileSnapshot, &testCollector{}) + err := Extractors(browser.UserDataDir{Browser: chrome}, input.Profile)[category.Extension].Extract(context.Background(), input, &testCollector{}) require.Error(t, err, "Chrome has no opsettings fallback") } diff --git a/internal/browser/extractor.go b/internal/browser/extractor.go index 2a75c3c..5794a94 100644 --- a/internal/browser/extractor.go +++ b/internal/browser/extractor.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/keychain" "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/snapshot" @@ -41,7 +42,7 @@ func (s Source) CandidatePaths(profile Profile) []string { type Extractor struct { Sources []Source - Extract func(ctx context.Context, profileSnapshot ProfileSnapshot, out Collector) error + Extract func(ctx context.Context, input Input, out Collector) error } type Extractors map[category.Category]Extractor @@ -52,21 +53,31 @@ type Collector interface { Fail(err error) } -type ProfileSnapshot struct { - Profile Profile - snapshot snapshot.Snapshot - masterKeys func(ctx context.Context) masterkey.Set +// LoginKeychain is what an extractor reads from the run's macOS login keychain. +type LoginKeychain interface { + InternetPasswords(ctx context.Context) ([]keychain.InternetPassword, error) } -// NewProfileSnapshot takes masterKeys, the dir's call-once retrieval, nil for bases that keep no Chromium keys. -func NewProfileSnapshot(dirSnapshot snapshot.Snapshot, profile Profile, masterKeys func(context.Context) masterkey.Set) ProfileSnapshot { - return ProfileSnapshot{Profile: profile, snapshot: dirSnapshot, masterKeys: masterKeys} +// Input is what an extractor reads for one profile: its captured files, the dir's master keys, and the run's keychain. +type Input struct { + Profile Profile + snapshot snapshot.Snapshot + masterKeys func(ctx context.Context) masterkey.Set + loginKeychain LoginKeychain +} + +// NewInput takes masterKeys, the dir's call-once retrieval, nil for bases that keep no Chromium keys, and the run's +// login keychain, nil off macOS and in a restore. +func NewInput( + dirSnapshot snapshot.Snapshot, profile Profile, masterKeys func(context.Context) masterkey.Set, loginKeychain LoginKeychain, +) Input { + return Input{Profile: profile, snapshot: dirSnapshot, masterKeys: masterKeys, loginKeychain: loginKeychain} } // Path skips a candidate that was never captured but returns the error of one whose copy failed. -func (ps ProfileSnapshot) Path(source Source) (string, error) { - for _, relativePath := range source.CandidatePaths(ps.Profile) { - capturedPath, err := ps.snapshot.Path(relativePath) +func (in Input) Path(source Source) (string, error) { + for _, relativePath := range source.CandidatePaths(in.Profile) { + capturedPath, err := in.snapshot.Path(relativePath) if errors.Is(err, fs.ErrNotExist) { continue } @@ -76,9 +87,13 @@ func (ps ProfileSnapshot) Path(source Source) (string, error) { } // MasterKeys may block on its first call; a key version that could not be retrieved is absent from the Set. -func (ps ProfileSnapshot) MasterKeys(ctx context.Context) masterkey.Set { - if ps.masterKeys == nil { +func (in Input) MasterKeys(ctx context.Context) masterkey.Set { + if in.masterKeys == nil { return nil } - return ps.masterKeys(ctx) + return in.masterKeys(ctx) +} + +func (in Input) LoginKeychain() LoginKeychain { + return in.loginKeychain } diff --git a/internal/browser/extractor_test.go b/internal/browser/extractor_test.go index 5ea5dc4..2299a30 100644 --- a/internal/browser/extractor_test.go +++ b/internal/browser/extractor_test.go @@ -22,37 +22,37 @@ func writeSnapshotFile(t *testing.T, root, relativePath string) string { return path } -func TestProfileSnapshotPath(t *testing.T) { +func TestInputPath(t *testing.T) { root := t.TempDir() legacyCookies := writeSnapshotFile(t, root, "chrome/Default/Cookies") localState := writeSnapshotFile(t, root, "chrome/Local State") dirSnapshot := snapshot.Open(root).Snapshot("chrome") - profileSnapshot := NewProfileSnapshot(dirSnapshot, Profile{Name: "Default", RelativePath: "Default"}, nil) + input := NewInput(dirSnapshot, Profile{Name: "Default", RelativePath: "Default"}, nil, nil) - got, err := profileSnapshot.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}) + got, err := input.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}) require.NoError(t, err) assert.Equal(t, legacyCookies, got, "a candidate that was never captured is skipped") - got, err = profileSnapshot.Path(Source{Path: "Local State", Shared: true}) + got, err = input.Path(Source{Path: "Local State", Shared: true}) require.NoError(t, err) assert.Equal(t, localState, got, "a shared source resolves under the user data dir, not the profile") - _, err = profileSnapshot.Path(Source{Path: "History"}) + _, err = input.Path(Source{Path: "History"}) require.ErrorIs(t, err, fs.ErrNotExist) } -func TestProfileSnapshotPath_FlatLayoutProfile(t *testing.T) { +func TestInputPath_FlatLayoutProfile(t *testing.T) { root := t.TempDir() history := writeSnapshotFile(t, root, "opera/History") - profileSnapshot := NewProfileSnapshot(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil) + input := NewInput(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil, nil) - got, err := profileSnapshot.Path(Source{Path: "History"}) + got, err := input.Path(Source{Path: "History"}) require.NoError(t, err) assert.Equal(t, history, got) } -// TestProfileSnapshotPath_FailedCopyIsReported makes a failed copy an error, not a reason to read a lower candidate. -func TestProfileSnapshotPath_FailedCopyIsReported(t *testing.T) { +// TestInputPath_FailedCopyIsReported makes a failed copy an error, not a reason to read a lower candidate. +func TestInputPath_FailedCopyIsReported(t *testing.T) { from := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(from, "Default", "Network", "Cookies"), 0o700)) writeSnapshotFile(t, from, "Default/Cookies") @@ -65,23 +65,23 @@ func TestProfileSnapshotPath_FailedCopyIsReported(t *testing.T) { {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Cookies"}, })) - profileSnapshot := NewProfileSnapshot(root.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil) - _, err = profileSnapshot.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}) + input := NewInput(root.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil, nil) + _, err = input.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}) require.Error(t, err) assert.NotErrorIs(t, err, fs.ErrNotExist) } -func TestProfileSnapshotMasterKeys(t *testing.T) { +func TestInputMasterKeys(t *testing.T) { dirSnapshot := snapshot.Open(t.TempDir()).Snapshot("chrome") - assert.Nil(t, NewProfileSnapshot(dirSnapshot, Profile{}, nil).MasterKeys(context.Background())) + assert.Nil(t, NewInput(dirSnapshot, Profile{}, nil, nil).MasterKeys(context.Background())) calls := 0 want := masterkey.Set{masterkey.V10: []byte("k")} - profileSnapshot := NewProfileSnapshot(dirSnapshot, Profile{}, func(context.Context) masterkey.Set { + input := NewInput(dirSnapshot, Profile{}, func(context.Context) masterkey.Set { calls++ return want - }) - assert.Equal(t, want, profileSnapshot.MasterKeys(context.Background())) + }, nil) + assert.Equal(t, want, input.MasterKeys(context.Background())) assert.Equal(t, 1, calls) } diff --git a/internal/browser/firefox/firefox.go b/internal/browser/firefox/firefox.go index c0621fa..c6f42f7 100644 --- a/internal/browser/firefox/firefox.go +++ b/internal/browser/firefox/firefox.go @@ -120,8 +120,8 @@ func Extractors(_ browser.UserDataDir, _ browser.Profile) browser.Extractors { func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor { return browser.Extractor{ Sources: []browser.Source{source}, - Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { - path, err := profileSnapshot.Path(source) + Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { + path, err := input.Path(source) if err != nil { return err } @@ -134,19 +134,19 @@ func newPlainExtractor(parse func(string, browser.Collector) error, source brows func newDecryptingExtractor(parse func(func() ([]byte, error), string, browser.Collector) error, source browser.Source) browser.Extractor { return browser.Extractor{ Sources: []browser.Source{source, keyStore}, - Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { - path, err := profileSnapshot.Path(source) + Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { + path, err := input.Path(source) if err != nil { return err } - masterKey := func() ([]byte, error) { return profileKey(profileSnapshot, path) } + masterKey := func() ([]byte, error) { return profileKey(input, path) } return parse(masterKey, path, out) }, } } -func profileKey(profileSnapshot browser.ProfileSnapshot, loginsPath string) ([]byte, error) { - key4Path, err := profileSnapshot.Path(keyStore) +func profileKey(input browser.Input, loginsPath string) ([]byte, error) { + key4Path, err := input.Path(keyStore) if err != nil { return nil, err } diff --git a/internal/browser/firefox/firefox_test.go b/internal/browser/firefox/firefox_test.go index a9feba5..b706a20 100644 --- a/internal/browser/firefox/firefox_test.go +++ b/internal/browser/firefox/firefox_test.go @@ -126,11 +126,11 @@ func TestDecryptingExtractor_WithoutKeyStore(t *testing.T) { encodedLogin := loginPBEBase64(t) logins := createTestJSON(t, "logins.json", fmt.Sprintf(`{"logins": [{"hostname": "https://a.test", "encryptedUsername": %q, "encryptedPassword": %q, "timeCreated": 1700000000000}]}`, encodedLogin, encodedLogin)) - profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"p/logins.json": logins}), - browser.Profile{Name: "p", RelativePath: "p"}, nil) + input := browser.NewInput(snapshotOf(t, map[string]string{"p/logins.json": logins}), + browser.Profile{Name: "p", RelativePath: "p"}, nil, nil) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), profileSnapshot, &out)) + require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 1) assert.Equal(t, "https://a.test", got[0].URL) @@ -142,13 +142,13 @@ func TestDecryptingExtractor_WithoutKeyStore(t *testing.T) { // TestPasswordExtractor_NoLoginsNeverReadsTheKey leaves key4.db unread without logins, so an unreadable one is harmless. func TestDecryptingExtractor_NoLoginsNeverReadsTheKey(t *testing.T) { - profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ + input := browser.NewInput(snapshotOf(t, map[string]string{ "p/logins.json": createTestJSON(t, "logins.json", `{"logins": []}`), "p/key4.db": createTestJSON(t, "key4.db", "not a database"), - }), browser.Profile{Name: "p", RelativePath: "p"}, nil) + }), browser.Profile{Name: "p", RelativePath: "p"}, nil, nil) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), profileSnapshot, &out)) + require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) assert.Empty(t, out.records) assert.Empty(t, out.fails) } @@ -165,7 +165,7 @@ func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) { want := map[string]string{"a.default": "Home", "b.work": "Work"} for _, profile := range []browser.Profile{{Name: "a.default", RelativePath: "a.default"}, {Name: "b.work", RelativePath: "b.work"}} { var out testCollector - require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewProfileSnapshot(dirSnapshot, profile, nil), &out)) + require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, nil), &out)) got := collected[record.History](t, &out) require.Len(t, got, 1, profile.Name) assert.Equal(t, want[profile.Name], got[0].Title, profile.Name) diff --git a/internal/browser/safari/extract_password.go b/internal/browser/safari/extract_password.go index f45e31b..51537d9 100644 --- a/internal/browser/safari/extract_password.go +++ b/internal/browser/safari/extract_password.go @@ -9,7 +9,12 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -func extractPasswords(ctx context.Context, loginKeychain LoginKeychain, out browser.Collector) error { +// extractPasswords reads no file, so it always runs; without a usable password the keychain yields metadata only. +func extractPasswords(ctx context.Context, input browser.Input, out browser.Collector) error { + loginKeychain := input.LoginKeychain() + if loginKeychain == nil { + return errNoKeychain + } passwords, err := loginKeychain.InternetPasswords(ctx) if err != nil { return err @@ -23,7 +28,7 @@ func extractPasswords(ctx context.Context, loginKeychain LoginKeychain, out brow out.Add(&record.Login{ URL: url, Username: internetPassword.Account, - Password: internetPassword.PlainPassword, + Password: internetPassword.Password, CreatedAt: internetPassword.Created.UTC(), Store: record.StoreLocal, }) diff --git a/internal/browser/safari/profiles.go b/internal/browser/safari/profiles.go index b226f4a..9572116 100644 --- a/internal/browser/safari/profiles.go +++ b/internal/browser/safari/profiles.go @@ -29,8 +29,8 @@ var unsafeNameChars = regexp.MustCompile(`[/\\:*?"<>|\x00-\x1f]+`) var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$`) // namedProfiles reads SafariTabs.db (authoritative), with a ReadDir fallback only if the DB itself is unreadable. -func namedProfiles(library string) []browser.Profile { - named, err := readNamedProfilesFromDB(library) +func namedProfiles(ctx context.Context, library string, id browser.UserDataDirID) []browser.Profile { + named, err := readNamedProfilesFromDB(ctx, library, id) if err != nil { named = readNamedProfilesFromDir(library) } @@ -38,7 +38,7 @@ func namedProfiles(library string) []browser.Profile { } // readNamedProfilesFromDB reads a copy, never Safari's live file; (nil, err) means unreadable, and any slice is final. -func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { +func readNamedProfilesFromDB(ctx context.Context, library string, id browser.UserDataDirID) ([]browser.Profile, error) { root, err := snapshot.Temp() if err != nil { return nil, err @@ -48,12 +48,12 @@ func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { log.Warnf("%v", err) } }() - if err := root.Capture(context.Background(), []snapshot.File{{ - UserDataDirID: discoveryUserDataDirID, UserDataDirPath: library, RelativePath: tabsDatabasePath, + if err := root.Capture(ctx, []snapshot.File{{ + UserDataDirID: string(id), UserDataDirPath: library, RelativePath: tabsDatabasePath, }}); err != nil { return nil, fmt.Errorf("copy SafariTabs.db: %w", err) } - path, err := root.Snapshot(discoveryUserDataDirID).Path(tabsDatabasePath) + path, err := root.Snapshot(string(id)).Path(tabsDatabasePath) if err != nil { return nil, fmt.Errorf("copy SafariTabs.db: %w", err) } diff --git a/internal/browser/safari/profiles_test.go b/internal/browser/safari/profiles_test.go index 06e3356..2e7c8b7 100644 --- a/internal/browser/safari/profiles_test.go +++ b/internal/browser/safari/profiles_test.go @@ -1,6 +1,7 @@ package safari import ( + "context" "database/sql" "os" "path/filepath" @@ -26,7 +27,7 @@ func libraryAt(t *testing.T, home string) (container string) { func discoverProfiles(t *testing.T, home string) []browser.Profile { t.Helper() - dirs, err := Discover(testBrowser(), browser.DiscoverOptions{HomeDir: home}) + dirs, err := Discover(context.Background(), testBrowser(), browser.DiscoverOptions{HomeDir: home}) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, browser.UserDataDirID("safari"), dirs[0].ID) @@ -47,7 +48,7 @@ func TestDiscover_DefaultOnly(t *testing.T) { } func TestDiscover_MissingSafariYieldsNothing(t *testing.T) { - dirs, err := Discover(testBrowser(), browser.DiscoverOptions{HomeDir: t.TempDir()}) + dirs, err := Discover(context.Background(), testBrowser(), browser.DiscoverOptions{HomeDir: t.TempDir()}) require.NoError(t, err) assert.Empty(t, dirs) } @@ -63,7 +64,7 @@ func TestDiscover_UnreadableSafariDirIsAnError(t *testing.T) { require.NoError(t, os.Chmod(library, 0o000)) defer func() { require.NoError(t, os.Chmod(library, 0o700)) }() - dirs, err := Discover(testBrowser(), browser.DiscoverOptions{HomeDir: home}) + dirs, err := Discover(context.Background(), testBrowser(), browser.DiscoverOptions{HomeDir: home}) require.Error(t, err) assert.Empty(t, dirs) } @@ -79,7 +80,7 @@ func TestDiscover_ProfilePathIsTheSafariDir(t *testing.T) { home := t.TempDir() libraryAt(t, home) options := browser.DiscoverOptions{HomeDir: home, ProfilePath: filepath.Join(copied, "Library", "SafariCopy")} - dirs, err := Discover(testBrowser(), options) + dirs, err := Discover(context.Background(), testBrowser(), options) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, filepath.Join(copied, "Library"), dirs[0].Path) diff --git a/internal/browser/safari/safari.go b/internal/browser/safari/safari.go index c778c6b..5429b35 100644 --- a/internal/browser/safari/safari.go +++ b/internal/browser/safari/safari.go @@ -11,8 +11,6 @@ import ( "path/filepath" "strings" - "github.com/moond4rk/keychainbreaker" - "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/category" ) @@ -22,19 +20,13 @@ const ( containerDir = "Containers/com.apple.Safari/Data/Library" namedProfilesDir = containerDir + "/Safari/Profiles" - defaultProfileName = "default" - discoveryUserDataDirID = "safari" + defaultProfileName = "default" ) var errNoKeychain = errors.New("no login keychain") -// LoginKeychain is the one method the password extractor reads from the run's login keychain. -type LoginKeychain interface { - InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) -} - // Discover makes the Safari directory the default profile; -p names another, whose parent replaces ~/Library. -func Discover(safariBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { +func Discover(ctx context.Context, safariBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { var errs []error var dirs []browser.UserDataDir for i, safariPath := range userDataDirPaths(safariBrowser, options) { @@ -45,9 +37,11 @@ func Discover(safariBrowser browser.Browser, options browser.DiscoverOptions) ([ continue } library := filepath.Dir(safariPath) - profiles := append([]browser.Profile{{Name: defaultProfileName, RelativePath: filepath.Base(safariPath)}}, namedProfiles(library)...) + id := safariBrowser.UserDataDirID(i) + defaultProfile := browser.Profile{Name: defaultProfileName, RelativePath: filepath.Base(safariPath)} + profiles := append([]browser.Profile{defaultProfile}, namedProfiles(ctx, library, id)...) disambiguateNames(profiles) - dirs = append(dirs, browser.UserDataDir{ID: safariBrowser.UserDataDirID(i), Browser: safariBrowser, Path: library, Profiles: profiles}) + dirs = append(dirs, browser.UserDataDir{ID: id, Browser: safariBrowser, Path: library, Profiles: profiles}) } return dirs, errors.Join(errs...) } @@ -65,14 +59,14 @@ func userDataDirPaths(safariBrowser browser.Browser, options browser.DiscoverOpt // Extractors builds a named profile's sources from Profile.RelativePath; its files sit under two dirs named for its UUID. // The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile reads them. -func Extractors(dir browser.UserDataDir, profile browser.Profile, loginKeychain LoginKeychain) browser.Extractors { +func Extractors(dir browser.UserDataDir, profile browser.Profile) browser.Extractors { if uuid, named := namedProfileUUID(profile); named { return namedProfileExtractors(dir, profile, uuid) } - return defaultProfileExtractors(profile, loginKeychain) + return defaultProfileExtractors(profile) } -func defaultProfileExtractors(profile browser.Profile, loginKeychain LoginKeychain) browser.Extractors { +func defaultProfileExtractors(profile browser.Profile) browser.Extractors { var ( history = browser.Source{Path: "History.db"} cookies = browser.Source{ @@ -86,7 +80,7 @@ func defaultProfileExtractors(profile browser.Profile, loginKeychain LoginKeycha webExtensions = browser.Source{Path: fromLibrary(profile, containerDir+"/Safari/WebExtensions/Extensions.plist"), Optional: true} ) return browser.Extractors{ - category.Password: newPasswordExtractor(loginKeychain), + category.Password: {Extract: extractPasswords}, category.History: newPlainExtractor(extractHistories, history), category.Cookie: newPlainExtractor(extractCookies, cookies), category.Bookmark: newPlainExtractor(extractBookmarks, bookmarks), @@ -140,8 +134,8 @@ func fromLibrary(profile browser.Profile, relativePath string) string { func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor { return browser.Extractor{ Sources: []browser.Source{source}, - Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { - captured, err := profileSnapshot.Path(source) + Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { + captured, err := input.Path(source) if err != nil { return err } @@ -150,16 +144,6 @@ func newPlainExtractor(parse func(string, browser.Collector) error, source brows } } -// newPasswordExtractor lists no file, so it always runs; without a usable password the keychain yields metadata only. -func newPasswordExtractor(loginKeychain LoginKeychain) browser.Extractor { - return browser.Extractor{Extract: func(ctx context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { - if loginKeychain == nil { - return errNoKeychain - } - return extractPasswords(ctx, loginKeychain, out) - }} -} - func downloadsOf(profileUUID string) func(string, browser.Collector) error { return func(path string, out browser.Collector) error { return extractDownloads(path, profileUUID, out) } } @@ -168,10 +152,10 @@ func downloadsOf(profileUUID string) func(string, browser.Collector) error { func newExtensionExtractor(sources ...browser.Source) browser.Extractor { return browser.Extractor{ Sources: sources, - Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { var paths []string for _, source := range sources { - captured, err := profileSnapshot.Path(source) + captured, err := input.Path(source) if errors.Is(err, fs.ErrNotExist) { continue } diff --git a/internal/browser/safari/safari_test.go b/internal/browser/safari/safari_test.go index c0e3aee..cade6a1 100644 --- a/internal/browser/safari/safari_test.go +++ b/internal/browser/safari/safari_test.go @@ -10,13 +10,13 @@ import ( "testing" "time" - "github.com/moond4rk/keychainbreaker" "github.com/moond4rk/plist" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/keychain" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) @@ -41,7 +41,7 @@ func sourcePaths(profile browser.Profile, extractors browser.Extractors) map[cat } func TestExtractors_DefaultProfileSources(t *testing.T) { - extractors := Extractors(libraryDir, defaultProfile, nil) + extractors := Extractors(libraryDir, defaultProfile) assert.Equal(t, map[category.Category][]string{ category.History: {"Safari/History.db"}, category.Cookie: {containerDir + "/Cookies/Cookies.binarycookies", "Cookies/Cookies.binarycookies"}, @@ -66,10 +66,10 @@ func TestExtractors_NamedProfileSources(t *testing.T) { category.Cookie: {store + "/Cookies/Cookies.binarycookies"}, category.Download: {"Safari/Downloads.plist"}, category.LocalStorage: {store + "/Origins"}, - }, sourcePaths(workProfile, Extractors(libraryDir, workProfile, nil))) + }, sourcePaths(workProfile, Extractors(libraryDir, workProfile))) copied := browser.UserDataDir{Profiles: []browser.Profile{{Name: "default", RelativePath: "SafariCopy"}, workProfile}} - assert.Equal(t, []string{"SafariCopy/Downloads.plist"}, sourcePaths(workProfile, Extractors(copied, workProfile, nil))[category.Download], + assert.Equal(t, []string{"SafariCopy/Downloads.plist"}, sourcePaths(workProfile, Extractors(copied, workProfile))[category.Download], "a named profile's downloads sit in the default profile's dir, whatever -p named it") } @@ -96,12 +96,12 @@ func writeTestPlist(t *testing.T, value any) string { return plistPath } -func extract(t *testing.T, dirSnapshot snapshot.Snapshot, profile browser.Profile, loginKeychain LoginKeychain, dataCategory category.Category) (*testCollector, error) { +func extract(t *testing.T, dirSnapshot snapshot.Snapshot, profile browser.Profile, loginKeychain browser.LoginKeychain, dataCategory category.Category) (*testCollector, error) { t.Helper() - extractor, ok := Extractors(libraryDir, profile, loginKeychain)[dataCategory] + extractor, ok := Extractors(libraryDir, profile)[dataCategory] require.Truef(t, ok, "no %s extractor for %s", dataCategory, profile.Name) var out testCollector - err := extractor.Extract(context.Background(), browser.NewProfileSnapshot(dirSnapshot, profile, nil), &out) + err := extractor.Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, loginKeychain), &out) return &out, err } @@ -143,20 +143,20 @@ func TestExtractors_ExtensionsFromTheSnapshot(t *testing.T) { } type fakeKeychain struct { - passwords []keychainbreaker.InternetPassword + passwords []keychain.InternetPassword err error calls int } -func (k *fakeKeychain) InternetPasswords(context.Context) ([]keychainbreaker.InternetPassword, error) { +func (k *fakeKeychain) InternetPasswords(context.Context) ([]keychain.InternetPassword, error) { k.calls++ return k.passwords, k.err } func TestExtractors_PasswordsFromTheKeychain(t *testing.T) { created := time.Date(2024, 3, 1, 9, 0, 0, 0, time.FixedZone("CET", 3600)) - loginKeychain := &fakeKeychain{passwords: []keychainbreaker.InternetPassword{ - {Protocol: "htps", Server: "github.com", Port: 443, Account: "alice", PlainPassword: "s3cret", Created: created}, + loginKeychain := &fakeKeychain{passwords: []keychain.InternetPassword{ + {Protocol: "htps", Server: "github.com", Port: 443, Account: "alice", Password: "s3cret", Created: created}, {Protocol: "htps", Server: "locked.test", Account: "bob"}, {Protocol: "htps", Server: "", Account: "nobody"}, {Protocol: "htps", Server: "anonymous.test", Account: ""}, @@ -181,7 +181,7 @@ func TestExtractors_PasswordsWithoutAKeychain(t *testing.T) { // TestExtractors_NamedProfileSkipsUserWideSources leaves the keychain and the untagged plists to the default profile. func TestExtractors_NamedProfileSkipsUserWideSources(t *testing.T) { - extractors := Extractors(libraryDir, workProfile, &fakeKeychain{}) + extractors := Extractors(libraryDir, workProfile) for _, dataCategory := range []category.Category{category.Password, category.Bookmark, category.Extension} { assert.NotContains(t, extractors, dataCategory) } diff --git a/internal/browser/userdatadir.go b/internal/browser/userdatadir.go index 243f1ba..df2a2dc 100644 --- a/internal/browser/userdatadir.go +++ b/internal/browser/userdatadir.go @@ -15,6 +15,9 @@ type UserDataDir struct { Browser Browser Path string Profiles []Profile + // VaultKind is set on a restored dir: the on-disk format its vault names. A discovered dir leaves it empty, and + // its browser's name picks the format. + VaultKind string } // Profile is one profile within a user data dir. Name is the output's profile value and never a path. diff --git a/internal/export/writer.go b/internal/export/writer.go index ed75ecd..f355c84 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -63,11 +63,6 @@ func (w *Writer) write(dataCategory category.Category, records []record.Record) if len(records) == 0 { return nil } - for _, row := range records { - if row.Category() != dataCategory { - return fmt.Errorf("%T is not a %s record", row, dataCategory) - } - } file, err := w.open(dataCategory) if err != nil { return err diff --git a/internal/export/writer_test.go b/internal/export/writer_test.go index eec9620..2af4a5d 100644 --- a/internal/export/writer_test.go +++ b/internal/export/writer_test.go @@ -85,18 +85,6 @@ func TestWrite_AppendsExtractionsInWriteOrder(t *testing.T) { assert.Equal(t, []record.History{*older, *busier, *quiet}, rows, "each extraction is sorted on its own, then appended") } -func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) { - dir := t.TempDir() - writer, err := NewWriter(dir, JSON, false) - require.NoError(t, err) - require.EqualError(t, writer.Write(category.Cookie, []record.Record{&record.Login{}}), "*record.Login is not a cookie record") - require.NoError(t, writer.Close()) - - entries, err := os.ReadDir(dir) - require.NoError(t, err) - assert.Empty(t, entries) -} - func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { dir := t.TempDir() writer, err := NewWriter(dir, JSON, false) diff --git a/internal/keychain/keychain.go b/internal/keychain/keychain.go new file mode 100644 index 0000000..d1ca0c2 --- /dev/null +++ b/internal/keychain/keychain.go @@ -0,0 +1,15 @@ +// Package keychain owns the user's macOS login keychain: one handle per run, opened on first use. +package keychain + +import "time" + +// InternetPassword is one internet password item; Password is empty while the keychain stays locked. +type InternetPassword struct { + Protocol string + Server string + Port uint32 + Path string + Account string + Password string + Created time.Time +} diff --git a/internal/keychain/keychain_darwin.go b/internal/keychain/keychain_darwin.go index 318ca70..fe852d2 100644 --- a/internal/keychain/keychain_darwin.go +++ b/internal/keychain/keychain_darwin.go @@ -1,4 +1,3 @@ -// Package keychain owns the user's macOS login keychain: one handle per run, opened on first use. package keychain import ( @@ -61,14 +60,26 @@ func (k *Keychain) GenericPassword(ctx context.Context, account string) ([]byte, } // InternetPasswords leaves the secrets empty when the keychain is locked. -func (k *Keychain) InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) { +func (k *Keychain) InternetPasswords(ctx context.Context) ([]InternetPassword, error) { if err := k.open(ctx); err != nil { return nil, err } - passwords, err := k.opened.InternetPasswords() + items, err := k.opened.InternetPasswords() if err != nil { return nil, fmt.Errorf("read internet passwords: %w", err) } + passwords := make([]InternetPassword, 0, len(items)) + for _, item := range items { + passwords = append(passwords, InternetPassword{ + Protocol: item.Protocol, + Server: item.Server, + Port: item.Port, + Path: item.Path, + Account: item.Account, + Password: item.PlainPassword, + Created: item.Created, + }) + } return passwords, nil } diff --git a/internal/record/record.go b/internal/record/record.go index 3fc6e17..3e67cde 100644 --- a/internal/record/record.go +++ b/internal/record/record.go @@ -1,14 +1,9 @@ package record -import ( - "time" - - "github.com/moond4rk/hackbrowserdata/internal/category" -) +import "time" // Record is one output row; the collector sets its Browser and Profile, so extractors leave both empty. type Record interface { - Category() category.Category SetBrowserAndProfile(browser, profile string) } @@ -123,16 +118,6 @@ type SessionStorage struct { Value string `json:"value" csv:"value"` } -func (r *Login) Category() category.Category { return category.Password } -func (r *Cookie) Category() category.Category { return category.Cookie } -func (r *Bookmark) Category() category.Category { return category.Bookmark } -func (r *History) Category() category.Category { return category.History } -func (r *Download) Category() category.Category { return category.Download } -func (r *CreditCard) Category() category.Category { return category.CreditCard } -func (r *Extension) Category() category.Category { return category.Extension } -func (r *LocalStorage) Category() category.Category { return category.LocalStorage } -func (r *SessionStorage) Category() category.Category { return category.SessionStorage } - func (r *Login) SetBrowserAndProfile(browser, profile string) { r.Browser, r.Profile = browser, profile } diff --git a/internal/record/record_test.go b/internal/record/record_test.go index 800d51e..e637af8 100644 --- a/internal/record/record_test.go +++ b/internal/record/record_test.go @@ -7,32 +7,11 @@ import ( "unicode" "github.com/stretchr/testify/assert" - - "github.com/moond4rk/hackbrowserdata/internal/category" ) -func allRecords() map[category.Category]Record { - return map[category.Category]Record{ - category.Password: &Login{}, - category.Cookie: &Cookie{}, - category.Bookmark: &Bookmark{}, - category.History: &History{}, - category.Download: &Download{}, - category.CreditCard: &CreditCard{}, - category.Extension: &Extension{}, - category.LocalStorage: &LocalStorage{}, - category.SessionStorage: &SessionStorage{}, - } -} - -func TestCategory_OneRecordTypePerCategory(t *testing.T) { - records := allRecords() - assert.Len(t, records, len(category.All())) - for _, dataCategory := range category.All() { - row, ok := records[dataCategory] - if assert.Truef(t, ok, "no record type for %s", dataCategory) { - assert.Equalf(t, dataCategory, row.Category(), "%T", row) - } +func allRecords() []Record { + return []Record{ + &Login{}, &Cookie{}, &Bookmark{}, &History{}, &Download{}, &CreditCard{}, &Extension{}, &LocalStorage{}, &SessionStorage{}, } }