diff --git a/cmd/hack-browser-data/list.go b/cmd/hack-browser-data/list.go index 8ce430b..10f14d2 100644 --- a/cmd/hack-browser-data/list.go +++ b/cmd/hack-browser-data/list.go @@ -1,15 +1,9 @@ package main import ( - "fmt" - "io" - "path/filepath" - "text/tabwriter" - "github.com/spf13/cobra" "github.com/moond4rk/hackbrowserdata/internal/app" - "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -22,7 +16,7 @@ func newListCommand() *cobra.Command { Example: ` hack-browser-data list hack-browser-data list --detail`, RunE: func(command *cobra.Command, args []string) error { - options, err := app.ListOptions() + options, err := app.ValidateList() if err != nil { return err } @@ -37,7 +31,7 @@ func newListCommand() *cobra.Command { if !detail { return printProfiles(command.OutOrStdout(), discovery) } - summary, err := app.CountRecords(command.Context(), discovery, options.Categories, options.Keychain) + summary, err := app.CountRecords(command.Context(), discovery, options.Keychain) if err != nil { return err } @@ -48,39 +42,3 @@ func newListCommand() *cobra.Command { command.Flags().BoolVar(&detail, "detail", false, "show per-category entry counts") return command } - -func printProfiles(out io.Writer, discovery app.Discovery) error { - table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) - fmt.Fprintln(table, "Browser\tProfile\tPath") - for _, dir := range discovery.Dirs { - for _, profile := range dir.Profiles { - profilePath := filepath.Join(dir.Path, filepath.FromSlash(profile.RelativePath)) - fmt.Fprintf(table, "%s\t%s\t%s\n", dir.Browser.DisplayName, profile.Name, profilePath) - } - } - return table.Flush() -} - -func printRecordCounts(out io.Writer, discovery app.Discovery, summary app.Summary) error { - counts := make(map[app.Extraction]int, len(summary.Results)) - for _, result := range summary.Results { - counts[result.Extraction] = result.Records - } - - table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) - fmt.Fprint(table, "Browser\tProfile") - for _, dataCategory := range category.All() { - fmt.Fprintf(table, "\t%s", dataCategory.String()) - } - fmt.Fprintln(table) - for _, dir := range discovery.Dirs { - for _, profile := range dir.Profiles { - fmt.Fprintf(table, "%s\t%s", dir.Browser.DisplayName, profile.Name) - for _, dataCategory := range category.All() { - fmt.Fprintf(table, "\t%d", counts[app.Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory}]) - } - fmt.Fprintln(table) - } - } - return table.Flush() -} diff --git a/cmd/hack-browser-data/main.go b/cmd/hack-browser-data/main.go index 777f49e..4ba2274 100644 --- a/cmd/hack-browser-data/main.go +++ b/cmd/hack-browser-data/main.go @@ -3,8 +3,6 @@ package main import ( "context" "errors" - "fmt" - "io" "os" "os/signal" "syscall" @@ -12,8 +10,6 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" - "github.com/moond4rk/hackbrowserdata/internal/app" - "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -73,40 +69,6 @@ func silenceWhenStopped(command *cobra.Command) { } } -// report prints the run's summary; it is not part of the output, so failing to print it never fails the run. -func report(writer io.Writer, summary app.Summary) { - if err := app.Report(writer, summary); err != nil { - log.Warnf("print summary: %v", err) - } -} - -// warnIfNothingFound reports discovery's failures, the likely reason it found no browser data, then says so. -func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message string) bool { - if len(discovery.Dirs) > 0 { - return false - } - if len(discovery.DirFailures) > 0 { - report(stderr, app.Summary{DirFailures: discovery.DirFailures}) - } - log.Warnf("%s", message) - return true -} - -// announceExport lists the files a run wrote, even when it stopped early, so the user finds what it left. -func announceExport(stderr io.Writer, exported export.Listing) { - if len(exported.Files) == 0 { - return - } - fmt.Fprintln(stderr) - log.Infof("Exported to %s/", exported.Dir) - for _, file := range exported.Files { - log.Infof(" %-24s %d entries", file.Name, file.Count) - } - if exported.ZipName != "" { - log.Infof("Compressed: %s/%s", exported.Dir, exported.ZipName) - } -} - // stopSignals end the process by default; each first cancels the run, so its temporary copies are removed. var stopSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP} diff --git a/cmd/hack-browser-data/report.go b/cmd/hack-browser-data/report.go new file mode 100644 index 0000000..60d35c2 --- /dev/null +++ b/cmd/hack-browser-data/report.go @@ -0,0 +1,103 @@ +package main + +import ( + "fmt" + "io" + "path/filepath" + "text/tabwriter" + + "github.com/moond4rk/hackbrowserdata/internal/app" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/export" + "github.com/moond4rk/hackbrowserdata/internal/log" +) + +// report prints the run's summary; it is not part of the output, so failing to print it never fails the run. +func report(stderr io.Writer, summary app.Summary) { + table := tabwriter.NewWriter(stderr, 0, 0, 2, ' ', 0) + fmt.Fprintln(table, "Browser\tProfile\tCategory\tResult\tRecords\tDetail") + for _, failure := range summary.DirFailures { + fmt.Fprintf(table, "%s\t-\t-\t%s\t0\t%s\n", failure.UserDataDirID, app.OutcomeError, failure.Err) + } + for _, result := range summary.Results { + fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%d\t%s\n", + result.UserDataDirID, result.ProfileName, result.Category, result.Outcome, result.Records, resultDetail(result)) + } + if err := table.Flush(); err != nil { + log.Warnf("print summary: %v", err) + } +} + +func resultDetail(result app.Result) string { + switch { + case result.Err != nil: + return result.Err.Error() + case result.Failures > 0: + return fmt.Sprintf("%d not recovered", result.Failures) + default: + return "" + } +} + +// warnIfNothingFound reports discovery's failures, the likely reason it found no browser data, then says so. +func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message string) bool { + if len(discovery.Dirs) > 0 { + return false + } + if len(discovery.DirFailures) > 0 { + report(stderr, app.Summary{DirFailures: discovery.DirFailures}) + } + log.Warnf("%s", message) + return true +} + +// announceExport lists the files a run wrote, even when it stopped early, so the user finds what it left. +func announceExport(stderr io.Writer, exported export.Listing) { + if len(exported.Files) == 0 { + return + } + fmt.Fprintln(stderr) + log.Infof("Exported to %s/", exported.Dir) + for _, file := range exported.Files { + log.Infof(" %-24s %d entries", file.Name, file.Count) + } + if exported.ZipName != "" { + log.Infof("Compressed: %s/%s", exported.Dir, exported.ZipName) + } +} + +func printProfiles(out io.Writer, discovery app.Discovery) error { + table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + fmt.Fprintln(table, "Browser\tProfile\tPath") + for _, dir := range discovery.Dirs { + for _, profile := range dir.Profiles { + profilePath := filepath.Join(dir.Path, filepath.FromSlash(profile.RelativePath)) + fmt.Fprintf(table, "%s\t%s\t%s\n", dir.Browser.DisplayName, profile.Name, profilePath) + } + } + return table.Flush() +} + +func printRecordCounts(out io.Writer, discovery app.Discovery, summary app.Summary) error { + counts := make(map[app.Extraction]int, len(summary.Results)) + for _, result := range summary.Results { + counts[result.Extraction] = result.Records + } + + table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + fmt.Fprint(table, "Browser\tProfile") + for _, dataCategory := range category.All() { + fmt.Fprintf(table, "\t%s", dataCategory.String()) + } + fmt.Fprintln(table) + for _, dir := range discovery.Dirs { + for _, profile := range dir.Profiles { + fmt.Fprintf(table, "%s\t%s", dir.Browser.DisplayName, profile.Name) + for _, dataCategory := range category.All() { + fmt.Fprintf(table, "\t%d", counts[app.Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory}]) + } + fmt.Fprintln(table) + } + } + return table.Flush() +} diff --git a/internal/app/report_test.go b/cmd/hack-browser-data/report_test.go similarity index 56% rename from internal/app/report_test.go rename to cmd/hack-browser-data/report_test.go index e8d00bc..eaee0b9 100644 --- a/internal/app/report_test.go +++ b/cmd/hack-browser-data/report_test.go @@ -1,4 +1,4 @@ -package app +package main import ( "bytes" @@ -9,23 +9,24 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/app" "github.com/moond4rk/hackbrowserdata/internal/category" ) func TestReport(t *testing.T) { - cookie := Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie} + cookie := app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie} var buffer bytes.Buffer - require.NoError(t, Report(&buffer, Summary{ - Results: []Result{ - {Extraction: cookie, Outcome: OutcomePartial, Records: 224, Failures: 4}, + report(&buffer, app.Summary{ + Results: []app.Result{ + {Extraction: cookie, Outcome: app.OutcomePartial, Records: 224, Failures: 4}, { - Extraction: Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Password}, - Outcome: OutcomeError, Failures: 2, Err: errors.New("password not decrypted"), + Extraction: app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Password}, + Outcome: app.OutcomeError, Failures: 2, Err: errors.New("password not decrypted"), }, - {Extraction: Extraction{UserDataDirID: "edge", ProfileName: "Default", Category: category.Password}}, + {Extraction: app.Extraction{UserDataDirID: "edge", ProfileName: "Default", Category: category.Password}}, }, - DirFailures: []DirFailure{{UserDataDirID: "arc-2", Err: errors.New("permission denied")}}, - })) + DirFailures: []app.DirFailure{{UserDataDirID: "arc-2", Err: errors.New("permission denied")}}, + }) lines := strings.Split(strings.TrimSpace(buffer.String()), "\n") require.Len(t, lines, 5) diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index 264cb85..2f16342 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "os" "github.com/spf13/cobra" @@ -43,7 +44,7 @@ func newRestoreCommand() *cobra.Command { } func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) error { - options, keyFile, err := app.ValidateRestore(flags) + options, err := app.ValidateRestore(flags, os.Stdin) if err != nil { return err } @@ -53,7 +54,7 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e } defer closeRestoreData(root) - discovery, keys, err := app.DiscoverRestore(root.Path(), keyFile, options.Target.BrowserName) + discovery, keys, err := app.DiscoverRestore(root.Path(), options.Vaults) if err != nil { return err } diff --git a/internal/app/archive.go b/internal/app/archive.go index 2272bfc..d495597 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -18,21 +18,26 @@ type ArchiveFlags struct { Categories string } +type ArchiveOptions struct { + Target Target + Categories []category.Category +} + // ValidateArchive takes no keychain password: an archive copies files and reads no secret. -func ValidateArchive(flags ArchiveFlags) (Options, error) { - browserName, err := parseBrowser(flags.Browser) +func ValidateArchive(flags ArchiveFlags) (ArchiveOptions, error) { + browsers, err := parseBrowsers(flags.Browser) if err != nil { - return Options{}, err + return ArchiveOptions{}, err } categories, err := parseCategories(flags.Categories) if err != nil { - return Options{}, err + return ArchiveOptions{}, err } home, err := homeDir() if err != nil { - return Options{}, err + return ArchiveOptions{}, err } - return Options{Target: Target{BrowserName: browserName, HomeDir: home}, Categories: categories}, nil + return ArchiveOptions{Target: Target{Browsers: browsers, HomeDir: home}, Categories: categories}, nil } // Archive returns how many files and directories it captured. diff --git a/internal/app/discover.go b/internal/app/discover.go index 9fa9cf3..0b8cb08 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -15,21 +15,14 @@ type Discovery struct { DirFailures []DirFailure } -// Discover applies the target's profile path only when one browser is named. func Discover(target Target) Discovery { var discovery Discovery - for _, supportedBrowser := range browser.Supported() { - if target.BrowserName != allBrowsers && supportedBrowser.Name != target.BrowserName { - continue - } - discoverOptions := browser.DiscoverOptions{HomeDir: target.HomeDir} - if target.BrowserName != allBrowsers { - discoverOptions.ProfilePath = target.ProfilePath - } - dirs, err := discover(supportedBrowser, discoverOptions) + discoverOptions := browser.DiscoverOptions{HomeDir: target.HomeDir, ProfilePath: target.ProfilePath} + for _, targetBrowser := range target.Browsers { + dirs, err := discover(targetBrowser, discoverOptions) discovery.Dirs = append(discovery.Dirs, withData(dirs)...) if err != nil { - discovery.DirFailures = append(discovery.DirFailures, DirFailure{UserDataDirID: browser.UserDataDirID(supportedBrowser.Name), Err: err}) + discovery.DirFailures = append(discovery.DirFailures, DirFailure{UserDataDirID: browser.UserDataDirID(targetBrowser.Name), Err: err}) } } return discovery diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index a1513e7..e318093 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -35,28 +35,24 @@ func TestDiscover(t *testing.T) { writeUserDataDir(t, home, "edge") writeUserDataDir(t, home, "chrome") - discovery := Discover(Target{BrowserName: "all", HomeDir: home}) + discovery := Discover(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{BrowserName: "edge", HomeDir: home}) + discovery = Discover(Target{Browsers: []browser.Browser{lookup(t, "edge")}, HomeDir: home}) assert.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery)) } -func TestDiscover_ProfilePathNeedsOneBrowser(t *testing.T) { +func TestDiscover_ProfilePath(t *testing.T) { home := t.TempDir() writeUserDataDir(t, home, "chrome") custom := t.TempDir() touch(t, custom, "Default", "Preferences") touch(t, custom, "Default", "History") - discovery := Discover(Target{BrowserName: "chrome", HomeDir: home, ProfilePath: custom}) + discovery := Discover(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) - - discovery = Discover(Target{BrowserName: "all", HomeDir: home, ProfilePath: custom}) - require.Len(t, discovery.Dirs, 1) - assert.NotEqual(t, custom, discovery.Dirs[0].Path, "-p is ignored without a specific browser") } // TestDiscover_KeepsOnlyProfilesWithData drops a never-used profile, which holds only its Preferences marker. @@ -67,7 +63,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{BrowserName: "all", HomeDir: home}) + discovery := Discover(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) } @@ -81,7 +77,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{BrowserName: "all", HomeDir: home}) + discovery := Discover(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/doc.go b/internal/app/doc.go index f4d8d7f..5b81a1c 100644 --- a/internal/app/doc.go +++ b/internal/app/doc.go @@ -1,2 +1,2 @@ -// Package app runs the pipeline: the Validate functions, Discover, Execute, and Report. +// Package app runs the pipeline's stages: the Validate functions, Discover, and Execute; cmd prints what they return. package app diff --git a/internal/app/dump.go b/internal/app/dump.go index 5ce9354..9b97f0f 100644 --- a/internal/app/dump.go +++ b/internal/app/dump.go @@ -5,6 +5,8 @@ import ( "fmt" "os" + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -19,45 +21,52 @@ type DumpFlags struct { ProfilePath string } +type DumpOptions struct { + Target Target + Categories []category.Category + Output Output + Keychain KeychainConfig +} + // ValidateDump checks every flag before any browser or secret is touched, so a bad flag fails fast. -func ValidateDump(flags DumpFlags, keychainPassword func(context.Context) (string, error)) (Options, error) { - browserName, err := parseBrowser(flags.Browser) +func ValidateDump(flags DumpFlags, keychainPassword func(context.Context) (string, error)) (DumpOptions, error) { + browsers, err := parseBrowsers(flags.Browser) if err != nil { - return Options{}, err + return DumpOptions{}, err } categories, err := parseCategories(flags.Categories) if err != nil { - return Options{}, err + return DumpOptions{}, err } format, err := export.ParseFormat(flags.Format) if err != nil { - return Options{}, err + return DumpOptions{}, err } if err := checkOutputDir(flags.OutputDir); err != nil { - return Options{}, err + return DumpOptions{}, err } - profilePath, err := checkProfilePath(browserName, flags.ProfilePath) + profilePath, err := checkProfilePath(browsers, flags.ProfilePath) if err != nil { - return Options{}, err + return DumpOptions{}, err } home, err := homeDir() if err != nil { - return Options{}, err + return DumpOptions{}, err } - return Options{ - Target: Target{BrowserName: browserName, ProfilePath: profilePath, HomeDir: home}, + return DumpOptions{ + Target: Target{Browsers: browsers, ProfilePath: profilePath, HomeDir: home}, Categories: categories, Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip}, - Keychain: KeychainConfig{HomeDir: home, Password: keychainPassword}, + Keychain: KeychainConfig{Path: loginKeychainPath(home), Password: keychainPassword}, }, nil } -// checkProfilePath keeps -p only when one browser is named; with -b all it is ignored, as it always was, but now said. -func checkProfilePath(browserName, path string) (string, error) { +// checkProfilePath keeps -p only for one browser; with -b all it is ignored, as it always was, but now said. +func checkProfilePath(browsers []browser.Browser, path string) (string, error) { if path == "" { return "", nil } - if browserName == allBrowsers { + if len(browsers) != 1 { log.Warnf("-p needs a specific -b; ignoring %s", path) return "", nil } diff --git a/internal/app/dump_test.go b/internal/app/dump_test.go index 2c7299e..5b2966f 100644 --- a/internal/app/dump_test.go +++ b/internal/app/dump_test.go @@ -20,19 +20,20 @@ func TestValidateDump(t *testing.T) { keychainPassword := func(context.Context) (string, error) { return "pw", nil } options, err := ValidateDump(DumpFlags{Browser: " Chrome ", Categories: "cookie, password,cookie", Format: "csv", OutputDir: "out"}, keychainPassword) require.NoError(t, err) - assert.Equal(t, "chrome", options.Target.BrowserName) + require.Len(t, options.Target.Browsers, 1) + assert.Equal(t, "chrome", options.Target.Browsers[0].Name) assert.Equal(t, []category.Category{category.Cookie, category.Password}, options.Categories, "a repeated category runs once") assert.Equal(t, export.CSV, options.Output.Format) assert.Equal(t, "out", options.Output.Dir) assert.NotEmpty(t, options.Target.HomeDir) - assert.Equal(t, options.Target.HomeDir, options.Keychain.HomeDir) + assert.Equal(t, loginKeychainPath(options.Target.HomeDir), options.Keychain.Path) password, err := options.Keychain.Password(context.Background()) require.NoError(t, err) assert.Equal(t, "pw", password) options, err = ValidateDump(DumpFlags{Categories: "all", Format: "json"}, nil) require.NoError(t, err) - assert.Equal(t, "all", options.Target.BrowserName) + assert.Equal(t, browser.Supported(), options.Target.Browsers) assert.Equal(t, category.All(), options.Categories) } diff --git a/internal/app/dumpkeys.go b/internal/app/dumpkeys.go index d5d7763..261971f 100644 --- a/internal/app/dumpkeys.go +++ b/internal/app/dumpkeys.go @@ -18,18 +18,23 @@ type DumpKeysFlags struct { Browser string } -func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword func(context.Context) (string, error)) (Options, error) { - browserName, err := parseBrowser(flags.Browser) +type DumpKeysOptions struct { + Target Target + Keychain KeychainConfig +} + +func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword func(context.Context) (string, error)) (DumpKeysOptions, error) { + browsers, err := parseBrowsers(flags.Browser) if err != nil { - return Options{}, err + return DumpKeysOptions{}, err } home, err := homeDir() if err != nil { - return Options{}, err + return DumpKeysOptions{}, err } - return Options{ - Target: Target{BrowserName: browserName, HomeDir: home}, - Keychain: KeychainConfig{HomeDir: home, Password: keychainPassword}, + return DumpKeysOptions{ + Target: Target{Browsers: browsers, HomeDir: home}, + Keychain: KeychainConfig{Path: loginKeychainPath(home), Password: keychainPassword}, }, nil } diff --git a/internal/app/keychain_darwin.go b/internal/app/keychain_darwin.go index ffcb1e9..1e98264 100644 --- a/internal/app/keychain_darwin.go +++ b/internal/app/keychain_darwin.go @@ -15,11 +15,14 @@ import ( // newLoginKeychain builds the run's login keychain without opening it, so a run that never decrypts never prompts. func newLoginKeychain(config KeychainConfig) loginKeychain { - path := filepath.Join(config.HomeDir, "Library", "Keychains", "login.keychain-db") if config.Password == nil { - return keychain.New(path, func(context.Context) (string, error) { return "", nil }) + return keychain.New(config.Path, func(context.Context) (string, error) { return "", nil }) } - return &reportingKeychain{Keychain: keychain.New(path, keychain.PasswordFunc(config.Password))} + return &reportingKeychain{Keychain: keychain.New(config.Path, keychain.PasswordFunc(config.Password))} +} + +func loginKeychainPath(home string) string { + return filepath.Join(home, "Library", "Keychains", "login.keychain-db") } // reportingKeychain says once why the keychain stayed locked, since every consumer then reads metadata only, quietly. diff --git a/internal/app/keychain_other.go b/internal/app/keychain_other.go index 400c77e..75a4936 100644 --- a/internal/app/keychain_other.go +++ b/internal/app/keychain_other.go @@ -3,3 +3,5 @@ package app func newLoginKeychain(KeychainConfig) loginKeychain { return nil } + +func loginKeychainPath(string) string { return "" } diff --git a/internal/app/list.go b/internal/app/list.go index 2f55a77..14a0505 100644 --- a/internal/app/list.go +++ b/internal/app/list.go @@ -3,30 +3,33 @@ package app import ( "context" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/record" ) -// ListOptions is what list reads: every browser and category, with the keychain left locked, so counting never prompts. -func ListOptions() (Options, error) { +type ListOptions struct { + Target Target + Keychain KeychainConfig +} + +// ValidateList targets every browser and leaves the keychain without a password, so counting never prompts. +func ValidateList() (ListOptions, error) { home, err := homeDir() if err != nil { - return Options{}, err + return ListOptions{}, err } - return Options{ - Target: Target{BrowserName: allBrowsers, HomeDir: home}, - Categories: category.All(), - Keychain: KeychainConfig{HomeDir: home}, + return ListOptions{ + Target: Target{Browsers: browser.Supported(), HomeDir: home}, + Keychain: KeychainConfig{Path: loginKeychainPath(home)}, }, nil } -// CountRecords runs with no key and the keychain locked, counting records instead of exporting them. -func CountRecords( - ctx context.Context, discovery Discovery, categories []category.Category, keychainConfig KeychainConfig, -) (Summary, 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)} - return counter.run(ctx, discovery, categories) + return counter.run(ctx, discovery, category.All()) } type discard struct{} diff --git a/internal/app/options.go b/internal/app/options.go index 5943a71..dd4d9aa 100644 --- a/internal/app/options.go +++ b/internal/app/options.go @@ -14,18 +14,10 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/export" ) -// Options are a command's validated flags, grouped by the stage that reads them; a command leaves the rest empty. -type Options struct { - Target Target - Categories []category.Category - Output Output - Keychain KeychainConfig -} - // Target is what Discover looks for. type Target struct { - BrowserName string // "all" or one Browser.Name - ProfilePath string // a custom profile dir, used only with one browser + Browsers []browser.Browser + ProfilePath string // a custom profile dir; set only when Browsers holds one browser HomeDir string } @@ -38,7 +30,7 @@ type Output struct { // KeychainConfig locates the macOS login keychain and says how to get its password; other systems ignore it. type KeychainConfig struct { - HomeDir string + Path string // Password runs when the keychain first opens; "" leaves it locked, and nil, as list has it, silently. Password func(ctx context.Context) (string, error) } @@ -53,18 +45,18 @@ func homeDir() (string, error) { const allBrowsers = "all" -// parseBrowser accepts all or one of this OS's browser names; a name from another OS's table has nothing to find here. -func parseBrowser(value string) (string, error) { +// parseBrowsers accepts all or one of this OS's browser names; a name from another OS's table has nothing to find here. +func parseBrowsers(value string) ([]browser.Browser, error) { name := strings.ToLower(strings.TrimSpace(value)) if name == "" || name == allBrowsers { - return allBrowsers, nil + return browser.Supported(), nil } for _, supportedBrowser := range browser.Supported() { if supportedBrowser.Name == name { - return name, nil + return []browser.Browser{supportedBrowser}, nil } } - return "", fmt.Errorf("unknown browser %q, available: %s|%s", value, allBrowsers, strings.Join(browser.Names(), "|")) + return nil, fmt.Errorf("unknown browser %q, available: %s|%s", value, allBrowsers, strings.Join(browser.Names(), "|")) } // parseCategories keeps a repeated category once, or its records would be exported twice. diff --git a/internal/app/report.go b/internal/app/report.go deleted file mode 100644 index 18fdcaa..0000000 --- a/internal/app/report.go +++ /dev/null @@ -1,32 +0,0 @@ -package app - -import ( - "fmt" - "io" - "text/tabwriter" -) - -// Report prints a summary that is not part of the output contract and never changes the exit status. -func Report(writer io.Writer, summary Summary) error { - table := tabwriter.NewWriter(writer, 0, 0, 2, ' ', 0) - fmt.Fprintln(table, "Browser\tProfile\tCategory\tResult\tRecords\tDetail") - for _, failure := range summary.DirFailures { - fmt.Fprintf(table, "%s\t-\t-\t%s\t0\t%s\n", failure.UserDataDirID, OutcomeError, failure.Err) - } - for _, result := range summary.Results { - fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%d\t%s\n", - result.UserDataDirID, result.ProfileName, result.Category, result.Outcome, result.Records, detail(result)) - } - return table.Flush() -} - -func detail(result Result) string { - switch { - case result.Err != nil: - return result.Err.Error() - case result.Failures > 0: - return fmt.Sprintf("%d not recovered", result.Failures) - default: - return "" - } -} diff --git a/internal/app/restore.go b/internal/app/restore.go index 3b2b328..da24c48 100644 --- a/internal/app/restore.go +++ b/internal/app/restore.go @@ -10,6 +10,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/masterkey" @@ -27,46 +28,66 @@ type RestoreFlags struct { Zip bool } -// ValidateRestore checks restore's flags and reads its keys before any data is opened. A restore's browsers are the -// key file's vaults, not this OS's table, so -b is checked against them. -func ValidateRestore(flags RestoreFlags) (Options, masterkey.KeyFile, error) { +type RestoreOptions struct { + Vaults []masterkey.Vault // the key file's vaults that -b selects + Categories []category.Category + Output Output +} + +// ValidateRestore checks restore's flags and reads its keys, from stdin for "-", before any data is opened. A restore's +// browsers are the key file's vaults, not this OS's table, so -b selects among them. +func ValidateRestore(flags RestoreFlags, stdin io.Reader) (RestoreOptions, error) { if flags.KeyFile == "" { - return Options{}, masterkey.KeyFile{}, errors.New("requires --keys (or - for stdin)") + return RestoreOptions{}, errors.New("requires --keys (or - for stdin)") } if (flags.DataDir == "") == (flags.DataZip == "") { - return Options{}, masterkey.KeyFile{}, errors.New("exactly one of --data-dir or --data-zip is required") + return RestoreOptions{}, errors.New("exactly one of --data-dir or --data-zip is required") } categories, err := parseCategories(flags.Categories) if err != nil { - return Options{}, masterkey.KeyFile{}, err + return RestoreOptions{}, err } format, err := export.ParseFormat(flags.Format) if err != nil { - return Options{}, masterkey.KeyFile{}, err + return RestoreOptions{}, err } if err := checkOutputDir(flags.OutputDir); err != nil { - return Options{}, masterkey.KeyFile{}, err + return RestoreOptions{}, err } if err := checkRestoreData(flags.DataDir, flags.DataZip); err != nil { - return Options{}, masterkey.KeyFile{}, err + return RestoreOptions{}, err } - keyFile, err := readKeyFile(flags.KeyFile) + keyFile, err := readKeyFile(flags.KeyFile, stdin) if err != nil { - return Options{}, masterkey.KeyFile{}, err + return RestoreOptions{}, err } - filter := strings.ToLower(strings.TrimSpace(flags.Browser)) - if filter == "" { - filter = allBrowsers + vaults, err := selectVaults(keyFile.Vaults, flags.Browser) + if err != nil { + return RestoreOptions{}, err } - if filter != allBrowsers && len(vaultsOf(keyFile, filter)) == 0 { - return Options{}, masterkey.KeyFile{}, fmt.Errorf("no vault for browser %q in keys (have: %s)", filter, vaultBrowserNames(keyFile.Vaults)) - } - options := Options{ - Target: Target{BrowserName: filter}, + return RestoreOptions{ + Vaults: vaults, Categories: categories, Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip}, + }, nil +} + +// selectVaults keeps the vaults of the browser -b names, or every vault when it names none. +func selectVaults(vaults []masterkey.Vault, browserName string) ([]masterkey.Vault, error) { + name := strings.ToLower(strings.TrimSpace(browserName)) + if name == "" || name == allBrowsers { + return vaults, nil } - return options, keyFile, nil + var selected []masterkey.Vault + for _, vault := range vaults { + if strings.EqualFold(vault.Browser, name) { + selected = append(selected, vault) + } + } + if len(selected) == 0 { + return nil, fmt.Errorf("no vault for browser %q in keys (have: %s)", name, vaultBrowserNames(vaults)) + } + return selected, nil } func checkRestoreData(dataDir, dataZip string) error { @@ -82,8 +103,8 @@ func checkRestoreData(dataDir, dataZip string) error { return nil } -func readKeyFile(path string) (masterkey.KeyFile, error) { - var reader io.Reader = os.Stdin +func readKeyFile(path string, stdin io.Reader) (masterkey.KeyFile, error) { + reader := stdin if path != "-" { file, err := os.Open(path) if err != nil { @@ -99,12 +120,9 @@ func readKeyFile(path string) (masterkey.KeyFile, error) { return keyFile, nil } -// DiscoverRestore rebuilds the user data dirs under root, and their keys, from the key file: each vault names a +// DiscoverRestore rebuilds the user data dirs under root, and their keys, from the vaults: each vault names a // subdirectory of root, or root is one browser's User Data. -func DiscoverRestore( - root string, keyFile masterkey.KeyFile, browserName string, -) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) { - vaults := vaultsOf(keyFile, browserName) +func DiscoverRestore(root string, vaults []masterkey.Vault) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) { archived := false for _, vault := range vaults { if dirExists(filepath.Join(root, string(vaultUserDataDirID(vault)))) { @@ -182,16 +200,6 @@ func vaultUserDataDirID(vault masterkey.Vault) browser.UserDataDirID { return browser.UserDataDirID(strings.ToLower(vault.Browser)) } -func vaultsOf(keyFile masterkey.KeyFile, filter string) []masterkey.Vault { - var out []masterkey.Vault - for _, vault := range keyFile.Vaults { - if filter == allBrowsers || strings.EqualFold(vault.Browser, filter) { - out = append(out, vault) - } - } - return out -} - func vaultBrowserNames(vaults []masterkey.Vault) string { keys := make([]string, 0, len(vaults)) for _, vault := range vaults { diff --git a/internal/app/restore_golden_test.go b/internal/app/restore_golden_test.go index 4f11daa..b9d651e 100644 --- a/internal/app/restore_golden_test.go +++ b/internal/app/restore_golden_test.go @@ -115,17 +115,17 @@ func restoreGolden(t *testing.T, flags app.RestoreFlags) string { if flags.Format == "" { flags.Format = "json" } - options, keyFile, err := app.ValidateRestore(flags) + options, err := app.ValidateRestore(flags, nil) require.NoError(t, err) - data := snapshot.Open(flags.DataDir) + root := snapshot.Open(flags.DataDir) if flags.DataZip != "" { - data, err = snapshot.Unzip(flags.DataZip) + root, err = snapshot.Unzip(flags.DataZip) require.NoError(t, err) } - defer data.Close() + defer root.Close() - discovery, keys, err := app.DiscoverRestore(data.Path(), keyFile, options.Target.BrowserName) + discovery, keys, err := app.DiscoverRestore(root.Path(), options.Vaults) require.NoError(t, err) _, err = app.ExecuteWithKeys(context.Background(), discovery, options.Categories, options.Output, keys) require.NoError(t, err) diff --git a/internal/app/restore_test.go b/internal/app/restore_test.go index 3162ab3..18f051e 100644 --- a/internal/app/restore_test.go +++ b/internal/app/restore_test.go @@ -49,14 +49,23 @@ func TestValidateRestore_RejectsBadInput(t *testing.T) { } { flags := base edit(&flags) - _, _, err := ValidateRestore(flags) + _, err := ValidateRestore(flags, nil) require.Error(t, err, name) } - options, keyFile, err := ValidateRestore(RestoreFlags{KeyFile: keys, DataDir: data, Browser: "Chrome", Categories: "all", Format: "json", OutputDir: t.TempDir()}) + options, err := ValidateRestore(RestoreFlags{KeyFile: keys, DataDir: data, Browser: "Chrome", Categories: "all", Format: "json", OutputDir: t.TempDir()}, nil) require.NoError(t, err) - assert.Equal(t, "chrome", options.Target.BrowserName) - assert.Len(t, keyFile.Vaults, 1) + require.Len(t, options.Vaults, 1) + assert.Equal(t, "chrome", options.Vaults[0].Browser) +} + +func TestValidateRestore_ReadsKeysFromTheGivenStdin(t *testing.T) { + keys, err := os.ReadFile(keysFile(t, testVault("chrome"), testVault("edge"))) + require.NoError(t, err) + flags := RestoreFlags{KeyFile: "-", DataDir: t.TempDir(), Categories: "all", Format: "json", OutputDir: t.TempDir()} + options, err := ValidateRestore(flags, bytes.NewReader(keys)) + require.NoError(t, err) + assert.Len(t, options.Vaults, 2) } func TestDiscoverRestore_SecondUserDataDir(t *testing.T) { @@ -66,9 +75,7 @@ func TestDiscoverRestore_SecondUserDataDir(t *testing.T) { second := testVault("arc") second.ID = "arc-2" second.Keys = masterkey.Set{masterkey.V10: []byte("arc-2")} - keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), testVault("arc"), second}} - - discovery, keys, err := DiscoverRestore(root, keyFile, "arc") + discovery, keys, err := DiscoverRestore(root, []masterkey.Vault{testVault("arc"), second}) require.NoError(t, err) assert.Equal(t, []browser.UserDataDirID{"arc", "arc-2"}, userDataDirIDs(discovery), "a vault's ID names its directory") assert.Equal(t, filepath.Join(root, "arc-2"), discovery.Dirs[1].Path) @@ -82,9 +89,9 @@ func TestDiscoverRestore_FromLayout(t *testing.T) { layoutProfile(t, root, "nightly") nightly := testVault("Nightly") nightly.Kind = "chromium-yandex" - keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), nightly, testVault("chrome"), testVault("edge")}} + vaults := []masterkey.Vault{testVault("chrome"), nightly, testVault("chrome"), testVault("edge")} - discovery, keys, err := DiscoverRestore(root, keyFile, "all") + discovery, keys, err := DiscoverRestore(root, vaults) 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) @@ -96,12 +103,10 @@ func TestDiscoverRestore_OneUserDataNeedsOneVault(t *testing.T) { root := t.TempDir() touch(t, root, "Default", "Preferences") touch(t, root, "Default", "History") - keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), testVault("edge")}} - - _, _, err := DiscoverRestore(root, keyFile, "all") + _, _, err := DiscoverRestore(root, []masterkey.Vault{testVault("chrome"), testVault("edge")}) require.Error(t, err) - discovery, _, err := DiscoverRestore(root, keyFile, "edge") + discovery, _, err := DiscoverRestore(root, []masterkey.Vault{testVault("edge")}) require.NoError(t, err) require.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery)) assert.Equal(t, root, discovery.Dirs[0].Path) diff --git a/rfcs/001-architecture.md b/rfcs/001-architecture.md index bbd5a1d..32a83e0 100644 --- a/rfcs/001-architecture.md +++ b/rfcs/001-architecture.md @@ -22,7 +22,7 @@ Every extraction — one category from one profile of one data directory — end ## Layers -- The command layer wires flags into the pipeline and holds what lives as long as the process: signals, the console window, the data a restore reads. +- The command layer wires flags into the pipeline, prints what it returns, and holds what lives as long as the process: signals, the console window, the data a restore reads. - The pipeline orchestrates, and it is the only place that knows every browser base. - Each browser base knows its own discovery and file formats. - Shared services sit below them: secret retrieval, pure crypto primitives, snapshot capture, and export.