refactor: pin CLI output and rename path fields (#711)

Step 1 of #710. Goldens pin what a run prints before the entry code moves, and the renames follow two naming rules added to RFC-001. No behavior change.
This commit is contained in:
Roger authored and GitHub committed 2026-11-21 19:18:07 +08:00
1 parent 9bd94261e1
commit 6ddfe48493
42 files changed
+520 -203

No files matched your search

+107
View File
@@ -0,0 +1,107 @@
package main
import (
"bytes"
"path/filepath"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/golden"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
)
// browsersPlaceholder stands for this OS's browser names, so one golden serves every OS.
const browsersPlaceholder = "<browsers>"
func TestHelpGolden(t *testing.T) {
var screens strings.Builder
for _, args := range [][]string{
{"-h"}, {"dump", "-h"}, {"dumpkeys", "-h"}, {"archive", "-h"}, {"restore", "-h"}, {"list", "-h"}, {"version", "-h"},
} {
_, screen, err := runRoot(args...)
require.NoError(t, err, args)
screens.WriteString(commandLine(args) + screen)
}
golden.Assert(t, "help.golden", screens.String())
}
// TestUsageErrorsGolden puts a marker where a run printed its usage: help.golden pins the wording, this pins when it shows.
func TestUsageErrorsGolden(t *testing.T) {
setHome(t, t.TempDir())
var screens strings.Builder
for _, args := range [][]string{
{"-b", "nosuch"},
{"dump", "-b", "nosuch"},
{"dump", "-c", "nosuch"},
{"dump", "-f", "xml"},
{"dump", "--max-storage-value", "-1"},
{"dump", "--keychain-pw", "secret", "--keychain-pw-stdin"},
{"dumpkeys", "-b", "nosuch"},
{"archive", "-c", "nosuch"},
{"restore"},
{"restore", "--keys", "keys.json"},
{"restore", "--keys", "keys.json", "--data-dir", "data", "--data-zip", "data.zip"},
{"list", "--nosuch"},
{"nosuch"},
} {
root, screen, err := runRoot(args...)
require.Error(t, err, args)
for _, command := range sortedCommands(root) {
usage := strings.ReplaceAll(command.UsageString(), browserNames(), browsersPlaceholder)
screen = strings.Replace(screen, usage, "<usage: "+command.CommandPath()+">\n", 1)
}
screens.WriteString(commandLine(args) + screen)
}
golden.Assert(t, "errors.golden", screens.String())
}
func TestNothingFound(t *testing.T) {
setHome(t, t.TempDir())
t.Run("dump creates no output dir", func(t *testing.T) {
outputDir := filepath.Join(t.TempDir(), "results")
_, _, err := runRoot("dump", "-d", outputDir)
require.NoError(t, err)
assert.NoDirExists(t, outputDir)
})
t.Run("archive creates no archive", func(t *testing.T) {
archivePath := filepath.Join(t.TempDir(), "browser-data.zip")
_, _, err := runRoot("archive", "-o", archivePath)
require.NoError(t, err)
assert.NoFileExists(t, archivePath)
})
t.Run("list says so", func(t *testing.T) {
_, screen, err := runRoot("list")
require.NoError(t, err)
assert.Equal(t, "No browsers found.\n", screen)
})
t.Run("dumpkeys prints a key file without vaults", func(t *testing.T) {
_, screen, err := runRoot("dumpkeys")
require.NoError(t, err)
keyFile, err := masterkey.ReadKeyFile(strings.NewReader(screen))
require.NoError(t, err)
assert.Empty(t, keyFile.Vaults)
})
}
// runRoot returns the root it ran, for its commands' usage texts, and everything the run printed.
func runRoot(args ...string) (*cobra.Command, string, error) {
var screen bytes.Buffer
root := newRootCommand()
root.SetOut(&screen)
root.SetErr(&screen)
root.SetArgs(args)
err := root.Execute()
return root, strings.ReplaceAll(screen.String(), browserNames(), browsersPlaceholder), err
}
func commandLine(args []string) string {
return "$ hack-browser-data " + strings.Join(args, " ") + "\n"
}
+2 -2
View File
@@ -54,9 +54,9 @@ func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychai
return nil
}
summary, err := app.Execute(ctx, discovery, options.Categories, options.Output, options.Keychain, options.FirefoxPassword)
announceExport(stderr, summary.Exported)
printExported(stderr, summary.Exported)
if ctx.Err() == nil {
report(stderr, summary)
printSummary(stderr, summary)
}
return err
}
+1 -1
View File
@@ -60,5 +60,5 @@ func userDataDirOf(t *testing.T, home, browserName string) string {
t.Helper()
namedBrowser, ok := browser.Lookup(browserName)
require.True(t, ok, browserName)
return filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0]))
return filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0]))
}
+5 -5
View File
@@ -12,8 +12,8 @@ import (
"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) {
// printSummary is not part of the output, so failing to print it never fails the run.
func printSummary(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 {
@@ -45,14 +45,14 @@ func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message strin
return false
}
if len(discovery.DirFailures) > 0 {
report(stderr, app.Summary{DirFailures: discovery.DirFailures})
printSummary(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) {
// printExported lists the files a run wrote, even when it stopped early, so the user finds what it left.
func printExported(stderr io.Writer, exported export.Listing) {
if len(exported.Files) == 0 {
return
}
+2 -2
View File
@@ -13,10 +13,10 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/category"
)
func TestReport(t *testing.T) {
func TestPrintSummary(t *testing.T) {
cookie := app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie}
var buffer bytes.Buffer
report(&buffer, app.Summary{
printSummary(&buffer, app.Summary{
Results: []app.Result{
{Extraction: cookie, Outcome: app.OutcomePartial, Records: 224, Failures: 4},
{
+2 -2
View File
@@ -63,9 +63,9 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e
return nil
}
summary, err := app.ExecuteWithKeys(ctx, discovery, options.Categories, options.Output, keys)
announceExport(stderr, summary.Exported)
printExported(stderr, summary.Exported)
if ctx.Err() == nil {
report(stderr, summary)
printSummary(stderr, summary)
}
return err
}
+51
View File
@@ -0,0 +1,51 @@
$ hack-browser-data -b nosuch
Error: unknown browser "nosuch", available: all|<browsers>
<usage: hack-browser-data>
$ hack-browser-data dump -b nosuch
Error: unknown browser "nosuch", available: all|<browsers>
<usage: hack-browser-data dump>
$ hack-browser-data dump -c nosuch
Error: unknown category: "nosuch", available: all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage
<usage: hack-browser-data dump>
$ hack-browser-data dump -f xml
Error: unsupported format: xml
<usage: hack-browser-data dump>
$ hack-browser-data dump --max-storage-value -1
Error: --max-storage-value must be >= 0 (0 means unlimited), got -1
<usage: hack-browser-data dump>
$ hack-browser-data dump --keychain-pw secret --keychain-pw-stdin
Error: if any flags in the group [keychain-pw keychain-pw-stdin] are set none of the others can be; [keychain-pw keychain-pw-stdin] were all set
<usage: hack-browser-data dump>
$ hack-browser-data dumpkeys -b nosuch
Error: unknown browser "nosuch", available: all|<browsers>
<usage: hack-browser-data dumpkeys>
$ hack-browser-data archive -c nosuch
Error: unknown category: "nosuch", available: all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage
<usage: hack-browser-data archive>
$ hack-browser-data restore
Error: required flag(s) "keys" not set
<usage: hack-browser-data restore>
$ hack-browser-data restore --keys keys.json
Error: exactly one of --data-dir or --data-zip is required
<usage: hack-browser-data restore>
$ hack-browser-data restore --keys keys.json --data-dir data --data-zip data.zip
Error: if any flags in the group [data-dir data-zip] are set none of the others can be; [data-dir data-zip] were all set
<usage: hack-browser-data restore>
$ hack-browser-data list --nosuch
Error: unknown flag: --nosuch
<usage: hack-browser-data list>
$ hack-browser-data nosuch
Error: unknown command "nosuch" for "hack-browser-data"
Run 'hack-browser-data --help' for usage.
+154
View File
@@ -0,0 +1,154 @@
$ hack-browser-data -h
hack-browser-data decrypts and exports browser data from Chromium-based
browsers, Firefox, and Safari on Windows, macOS, and Linux.
GitHub: https://github.com/moonD4rk/HackBrowserData
Usage:
hack-browser-data [flags]
hack-browser-data [command]
Available Commands:
archive Pack decryption-relevant profile files into a zip for cross-host restore
dump Extract and decrypt browser data (default command)
dumpkeys Export Chromium master keys as JSON for cross-host decryption
help Help about any command
list List detected browsers and profiles
restore Decrypt copied profile data using exported master keys
version Print version information
Flags:
-b, --browser string target browser: all|<browsers> (default "all")
-c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all")
-d, --dir string output directory (default "results")
--firefox-pw string Firefox primary password (visible in ps and shell history)
--firefox-pw-stdin[=true|false] read the Firefox primary password from the first line of stdin
-f, --format string output format: csv|json|cookie-editor (default "json")
-h, --help[=true|false] help for hack-browser-data
--keychain-pw string macOS keychain password (visible in ps and shell history)
--keychain-pw-stdin[=true|false] read the macOS keychain password from the first line of stdin
--max-storage-value int max storage value chars, 0=unlimited (default 2048)
-p, --profile-path string custom profile dir path, get with chrome://version
-v, --verbose[=true|false] enable debug logging
--zip[=true|false] compress output to zip
Use "hack-browser-data [command] --help" for more information about a command.
$ hack-browser-data dump -h
Extract and decrypt browser data (default command)
Usage:
hack-browser-data dump [flags]
Examples:
hack-browser-data dump
hack-browser-data dump -b chrome -c password,cookie
hack-browser-data dump -b chrome -f json -d output
hack-browser-data dump -f cookie-editor
hack-browser-data dump --zip
Flags:
-b, --browser string target browser: all|<browsers> (default "all")
-c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all")
-d, --dir string output directory (default "results")
--firefox-pw string Firefox primary password (visible in ps and shell history)
--firefox-pw-stdin[=true|false] read the Firefox primary password from the first line of stdin
-f, --format string output format: csv|json|cookie-editor (default "json")
-h, --help[=true|false] help for dump
--keychain-pw string macOS keychain password (visible in ps and shell history)
--keychain-pw-stdin[=true|false] read the macOS keychain password from the first line of stdin
--max-storage-value int max storage value chars, 0=unlimited (default 2048)
-p, --profile-path string custom profile dir path, get with chrome://version
--zip[=true|false] compress output to zip
Global Flags:
-v, --verbose[=true|false] enable debug logging
$ hack-browser-data dumpkeys -h
Export Chromium master keys as JSON for cross-host decryption
Usage:
hack-browser-data dumpkeys [flags]
Examples:
hack-browser-data dumpkeys -o keys.json
hack-browser-data dumpkeys -b chrome
Flags:
-b, --browser string target browser: all|<browsers> (default "all")
-h, --help[=true|false] help for dumpkeys
--keychain-pw string macOS keychain password (visible in ps and shell history)
--keychain-pw-stdin[=true|false] read the macOS keychain password from the first line of stdin
-o, --output string output file (default: stdout)
Global Flags:
-v, --verbose[=true|false] enable debug logging
$ hack-browser-data archive -h
Pack decryption-relevant profile files into a zip for cross-host restore
Usage:
hack-browser-data archive [flags]
Examples:
hack-browser-data archive
hack-browser-data archive -b chrome -c cookie -o chrome-cookies.zip
Flags:
-b, --browser string target browser: all|<browsers> (default "all")
-c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all")
-h, --help[=true|false] help for archive
-o, --output string output archive of decryption-relevant browser files (default "browser-data.zip")
Global Flags:
-v, --verbose[=true|false] enable debug logging
$ hack-browser-data restore -h
Decrypt copied profile data using exported master keys
Usage:
hack-browser-data restore [flags]
Examples:
hack-browser-data restore --keys keys.json --data-zip data.zip
hack-browser-data restore --keys keys.json --data-dir ./data -b chrome -c cookie
hack-browser-data restore --keys keys.json --data-dir ./chrome-userdata -b chrome
ssh origin "hack-browser-data dumpkeys" | hack-browser-data restore --keys - --data-zip data.zip
Flags:
-b, --browser string restore only this browser (optional; must match a vault in --keys)
-c, --category string data categories (comma-separated): all|password,cookie,bookmark,history,download,creditcard,extension,localstorage,sessionstorage (default "all")
--data-dir string copied profile data dir (archive layout, or one browser's User Data with -b)
--data-zip string zip produced by the archive command (alternative to --data-dir)
-d, --dir string output directory (default "results")
-f, --format string output format: csv|json|cookie-editor (default "json")
-h, --help[=true|false] help for restore
--keys string keys file from dumpkeys (use - for stdin)
--max-storage-value int max storage value chars, 0=unlimited (default 2048)
--zip[=true|false] compress output to zip
Global Flags:
-v, --verbose[=true|false] enable debug logging
$ hack-browser-data list -h
List detected browsers and profiles
Usage:
hack-browser-data list [flags]
Examples:
hack-browser-data list
hack-browser-data list --detail
Flags:
--detail[=true|false] show per-category entry counts
-h, --help[=true|false] help for list
Global Flags:
-v, --verbose[=true|false] enable debug logging
$ hack-browser-data version -h
Print version information
Usage:
hack-browser-data version [flags]
Flags:
-h, --help[=true|false] help for version
Global Flags:
-v, --verbose[=true|false] enable debug logging
+1 -1
View File
@@ -50,7 +50,7 @@ func Archive(ctx context.Context, discovery Discovery, categories []category.Cat
}
files := archiveFiles(dirs, categories)
root, err := snapshot.Temp()
root, err := snapshot.NewRoot()
if err != nil {
return 0, err
}
+1 -1
View File
@@ -80,7 +80,7 @@ func TestArchiveGolden(t *testing.T) {
home := t.TempDir()
namedBrowser, ok := browser.Lookup(archiveLayoutBrowser)
require.True(t, ok)
archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])))
archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0])))
tests := []struct {
name string
+2 -2
View File
@@ -16,8 +16,8 @@ import (
func writeUserDataDir(t *testing.T, home, browserName string) string {
t.Helper()
namedBrowser := lookup(t, browserName)
require.NotEmpty(t, namedBrowser.Platform().UserDataDirs, browserName)
path := filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0]))
require.NotEmpty(t, namedBrowser.Platform().UserDataDirPaths, browserName)
path := filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0]))
touch(t, path, "Default", "Preferences")
touch(t, path, "Default", "History")
return path
+2 -2
View File
@@ -25,7 +25,7 @@ type DumpFlags struct {
type DumpOptions struct {
Target Target
Categories []category.Category
Output Output
Output OutputOptions
Keychain KeychainConfig
FirefoxPassword func(ctx context.Context) (string, error) // nil is the empty password; Execute reads it at most once
}
@@ -61,7 +61,7 @@ func ValidateDump(flags DumpFlags, keychainPassword, firefoxPassword func(contex
return DumpOptions{
Target: Target{Browsers: browsers, ProfilePath: profilePath, HomeDir: home},
Categories: categories,
Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue},
Output: OutputOptions{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue},
Keychain: KeychainConfig{Path: loginKeychainPath(home), Password: keychainPassword},
FirefoxPassword: firefoxPassword,
}, nil
+1 -1
View File
@@ -67,7 +67,7 @@ func otherOSBrowser(t *testing.T) string {
for _, name := range []string{"sogou", "safari"} {
namedBrowser, ok := browser.Lookup(name)
require.True(t, ok, name)
if len(namedBrowser.Platform().UserDataDirs) == 0 {
if len(namedBrowser.Platform().UserDataDirPaths) == 0 {
return name
}
}
+2 -2
View File
@@ -100,14 +100,14 @@ func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (m
}
func retrieveDirKeys(ctx context.Context, dir browser.UserDataDir, keys dirKeysFunc) (masterkey.Set, error) {
root, err := snapshot.Temp()
root, err := snapshot.NewRoot()
if err != nil {
return nil, err
}
defer closeRoot(root)
var files []snapshot.File
for _, source := range chromium.KeySources() {
if file, ok, err := firstOnDisk(dir, source.Paths(), source.IsDir); err == nil && ok {
if file, ok, err := firstOnDisk(dir, source.RelativePaths(), source.IsDir); err == nil && ok {
files = append(files, file)
}
}
+7 -4
View File
@@ -19,7 +19,7 @@ import (
// dir's copies are on disk. Its error means the run ended early; like os.ReadDir, it still returns the Summary of what
// ran before it, with the files written, so the caller can list them.
func Execute(
ctx context.Context, discovery Discovery, categories []category.Category, output Output, keychainConfig KeychainConfig,
ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions, keychainConfig KeychainConfig,
firefoxPassword func(context.Context) (string, error),
) (Summary, error) {
keychain := newLoginKeychain(keychainConfig)
@@ -46,13 +46,16 @@ func readOnce(read func(context.Context) (string, error)) func(context.Context)
// 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,
ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions,
keys map[browser.UserDataDirID]masterkey.Set,
) (Summary, error) {
return execute(ctx, discovery, categories, output, runner{extractors: extractorsFor, retrieveKeys: keysFromFile(keys)})
}
// 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) {
func execute(
ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions, dirRunner runner,
) (Summary, error) {
writer, err := export.NewWriter(output.Dir, output.Format, output.Zip)
if err != nil {
return Summary{}, err
@@ -106,7 +109,7 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories
log.Infof("Extracting %s...", dir.Browser.DisplayName)
}
root, err := snapshot.Temp()
root, err := snapshot.NewRoot()
if err != nil {
summary.Results = append(summary.Results, failAll(plan.extractions, err)...)
return summary, nil
+7 -7
View File
@@ -22,7 +22,7 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
var history = browser.Source{Path: "History"}
var history = browser.Source{RelativePath: "History"}
type extractFunc func(ctx context.Context, input browser.Input, out browser.Collector) error
@@ -56,7 +56,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()}
output := OutputOptions{Dir: t.TempDir()}
summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, runner{extractors: base, retrieveKeys: keys})
require.NoError(t, err)
return summary, output.Dir
@@ -136,7 +136,7 @@ func TestExecute_ReportsEachDirWhatNeverRanFirst(t *testing.T) {
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()}, runner{extractors: base, retrieveKeys: noKeys(t)})
summary, err := execute(context.Background(), discovery, categories, OutputOptions{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
@@ -233,7 +233,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()}, runner{extractors: base, retrieveKeys: noKeys(t)})
_, err := execute(ctx, discovery, categories, OutputOptions{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])
@@ -258,7 +258,7 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) {
return nil
},
})
output := Output{Dir: t.TempDir()}
output := OutputOptions{Dir: t.TempDir()}
require.NoError(t, os.Chmod(output.Dir, 0o500))
defer func() { require.NoError(t, os.Chmod(output.Dir, 0o700)) }()
@@ -275,7 +275,7 @@ func TestExecute_FirefoxPasswordReadOnce(t *testing.T) {
home := t.TempDir()
firefoxBrowser, ok := browser.Lookup("firefox")
require.True(t, ok)
profilesDir := filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirs[0]))
profilesDir := filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirPaths[0]))
globalSalt, masterKey := bytes.Repeat([]byte("16-byte-salt-abc"), 3), []byte("firefox-pw-master-key-24")
for _, profile := range []string{"a.default", "b.work"} {
browsertest.WriteFirefoxPrimaryPasswordProfile(t, filepath.Join(profilesDir, profile), globalSalt, []byte("hunter2"), [][]byte{masterKey})
@@ -287,7 +287,7 @@ func TestExecute_FirefoxPasswordReadOnce(t *testing.T) {
}
discovery := Discover(context.Background(), Target{Browsers: []browser.Browser{firefoxBrowser}, HomeDir: home})
summary, err := Execute(context.Background(), discovery, []category.Category{category.Password}, Output{Dir: t.TempDir()}, KeychainConfig{}, password)
summary, err := Execute(context.Background(), discovery, []category.Category{category.Password}, OutputOptions{Dir: t.TempDir()}, KeychainConfig{}, password)
require.NoError(t, err)
require.Len(t, summary.Results, 2)
for _, result := range summary.Results {
+2 -2
View File
@@ -24,7 +24,7 @@ func TestExtractGolden(t *testing.T) {
namedBrowser, ok := browser.Lookup(fixture.Name)
require.True(t, ok, fixture.Name)
require.Equal(t, fixture.DisplayName, namedBrowser.DisplayName, "records carry the table's display name")
browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])), fixture.Name)
browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0])), fixture.Name)
keys[browser.UserDataDirID(fixture.Name)] = browsertest.ChromiumKeys
}
@@ -37,7 +37,7 @@ func TestExtractGoldenFirefox(t *testing.T) {
home := t.TempDir()
firefoxBrowser, ok := browser.Lookup("firefox")
require.True(t, ok)
browsertest.WriteFirefoxUserDataDir(t, filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirs[0])))
browsertest.WriteFirefoxUserDataDir(t, filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirPaths[0])))
assertExtractGoldens(t, "extract-firefox", func(t *testing.T, format string) string {
return extractGoldenRun(t, home, nil, format)
+8 -8
View File
@@ -21,8 +21,8 @@ type Target struct {
HomeDir string
}
// Output is where and how Execute writes records.
type Output struct {
// OutputOptions is where and how Execute writes records.
type OutputOptions struct {
Dir string
Format export.Format
Zip bool
@@ -99,24 +99,24 @@ func parseCategories(value string) ([]category.Category, error) {
}
// checkOutputDir creates nothing: -d, or its nearest existing ancestor, must be a directory we can create in.
func checkOutputDir(dir string) error {
path := filepath.Clean(dir)
func checkOutputDir(outputDir string) error {
path := filepath.Clean(outputDir)
for {
info, err := os.Stat(path)
switch {
case err == nil && info.IsDir():
if err := canCreateIn(path); err != nil {
return fmt.Errorf("output dir %s: %w", dir, err)
return fmt.Errorf("output dir %s: %w", outputDir, err)
}
return nil
case err == nil:
return fmt.Errorf("output dir %s: %s is not a directory", dir, path)
return fmt.Errorf("output dir %s: %s is not a directory", outputDir, path)
case !errors.Is(err, fs.ErrNotExist):
return fmt.Errorf("output dir %s: %w", dir, err)
return fmt.Errorf("output dir %s: %w", outputDir, err)
}
parent := filepath.Dir(path)
if parent == path {
return fmt.Errorf("output dir %s: no existing parent directory", dir)
return fmt.Errorf("output dir %s: no existing parent directory", outputDir)
}
path = parent
}
+2 -2
View File
@@ -32,7 +32,7 @@ type RestoreFlags struct {
type RestoreOptions struct {
Vaults []masterkey.Vault // the key file's vaults that -b selects
Categories []category.Category
Output Output
Output OutputOptions
}
// ValidateRestore checks restore's flags and reads its keys, from stdin for "-", before any data is opened. A restore's
@@ -72,7 +72,7 @@ func ValidateRestore(flags RestoreFlags, stdin io.Reader) (RestoreOptions, error
return RestoreOptions{
Vaults: vaults,
Categories: categories,
Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue},
Output: OutputOptions{Dir: flags.OutputDir, Format: format, Zip: flags.Zip, MaxStorageValue: flags.MaxStorageValue},
}, nil
}
+1 -1
View File
@@ -65,7 +65,7 @@ func TestArchiveRestoreRoundTrip(t *testing.T) {
for _, fixture := range browsertest.ChromiumUserDataDirs {
namedBrowser, ok := browser.Lookup(fixture.Name)
require.True(t, ok, fixture.Name)
browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])), fixture.Name)
browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirPaths[0])), fixture.Name)
}
options, err := app.ValidateArchive(app.ArchiveFlags{Browser: "all", Categories: "all"})
require.NoError(t, err)
+3 -3
View File
@@ -28,9 +28,9 @@ const (
Safari
)
// Platform is one OS's half of a Browser; one without UserDataDirs means the browser is not supported there.
// Platform is one OS's half of a Browser; one without UserDataDirPaths means the browser is not supported there.
type Platform struct {
UserDataDirs []string // slash-separated, relative to the home directory; globs allowed
UserDataDirPaths []string // slash-separated, relative to the home directory; globs allowed
SecretLabel string // macOS Keychain account / Linux Secret Service label; "" = none
PortalAppID string // Linux: the app id whose XDG portal secret decrypts v12 values; "" = none
Executable string // Windows: the program the ABE payload is injected into
@@ -42,7 +42,7 @@ type Platform struct {
func Supported() []Browser {
var out []Browser
for _, browser := range browsers {
if len(browser.Platform().UserDataDirs) > 0 {
if len(browser.Platform().UserDataDirPaths) > 0 {
out = append(out, browser)
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ var platformOf = map[string]func(Browser) Platform{
func namesOn(platform func(Browser) Platform) []string {
var names []string
for _, browser := range browsers {
if len(platform(browser).UserDataDirs) > 0 {
if len(platform(browser).UserDataDirPaths) > 0 {
names = append(names, browser.Name)
}
}
+5 -5
View File
@@ -58,7 +58,7 @@ func DiscoverAt(chromiumBrowser browser.Browser, vaultKind string, id browser.Us
// profileAt takes chrome://version's path: a profile dir without Local State selects that profile of its parent.
func profileAt(chromiumBrowser browser.Browser, path string) (browser.UserDataDir, bool) {
if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.Paths()) {
if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.RelativePaths()) {
return browser.UserDataDir{}, false
}
clean := filepath.Clean(path)
@@ -80,7 +80,7 @@ func userDataDirPaths(chromiumBrowser browser.Browser, options browser.DiscoverO
paths []string
errs []error
)
for _, relativePath := range chromiumBrowser.Platform().UserDataDirs {
for _, relativePath := range chromiumBrowser.Platform().UserDataDirPaths {
matches, err := filepath.Glob(options.HomeDir + "/" + relativePath)
if err != nil {
errs = append(errs, fmt.Errorf("user data dir %q: %w", relativePath, err))
@@ -144,7 +144,7 @@ func profileFilePaths(dir browser.UserDataDir) []string {
for _, extractor := range kindExtractors(vaultKindOf(dir)) {
for _, source := range extractor.Sources {
if !source.Shared {
paths = append(paths, source.Paths()...)
paths = append(paths, source.RelativePaths()...)
}
}
}
@@ -167,7 +167,7 @@ func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterk
SecretLabel: platform.SecretLabel, Executable: platform.Executable, ExecutableFallbacks: platform.ExecutableFallbacks, ABE: platform.ABE,
PortalAppID: portalAppID(dir.Path, platform.PortalAppID),
}
path, err := dirSnapshot.Path(localState.Path)
path, err := dirSnapshot.Path(localState.RelativePath)
switch {
case err == nil:
locator.LocalState = path
@@ -205,7 +205,7 @@ func KeySources() []browser.Source {
func ArchiveSources() []browser.Source {
sources := KeySources()
for _, marker := range profileMarkers {
sources = append(sources, browser.Source{Path: marker, Optional: true})
sources = append(sources, browser.Source{RelativePath: marker, Optional: true})
}
return sources
}
+13 -13
View File
@@ -11,19 +11,19 @@ import (
)
var (
localState = browser.Source{Path: "Local State", Shared: true, Optional: true}
loginData = browser.Source{Path: "Login Data", Optional: true}
loginDataForAccount = browser.Source{Path: accountLoginData, Optional: true}
cookies = browser.Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}
bookmarks = browser.Source{Path: "Bookmarks"}
history = browser.Source{Path: "History"}
webData = browser.Source{Path: "Web Data"}
securePreferences = browser.Source{Path: "Secure Preferences"}
preferences = browser.Source{Path: "Preferences", Optional: true}
localStorage = browser.Source{Path: "Local Storage/leveldb", IsDir: true}
sessionStorage = browser.Source{Path: "Session Storage", IsDir: true}
yaPassmanData = browser.Source{Path: "Ya Passman Data"}
yaCreditCards = browser.Source{Path: "Ya Credit Cards"}
localState = browser.Source{RelativePath: "Local State", Shared: true, Optional: true}
loginData = browser.Source{RelativePath: "Login Data", Optional: true}
loginDataForAccount = browser.Source{RelativePath: accountLoginData, Optional: true}
cookies = browser.Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}
bookmarks = browser.Source{RelativePath: "Bookmarks"}
history = browser.Source{RelativePath: "History"}
webData = browser.Source{RelativePath: "Web Data"}
securePreferences = browser.Source{RelativePath: "Secure Preferences"}
preferences = browser.Source{RelativePath: "Preferences", Optional: true}
localStorage = browser.Source{RelativePath: "Local Storage/leveldb", IsDir: true}
sessionStorage = browser.Source{RelativePath: "Session Storage", IsDir: true}
yaPassmanData = browser.Source{RelativePath: "Ya Passman Data"}
yaCreditCards = browser.Source{RelativePath: "Ya Credit Cards"}
)
var defaultExtractors = browser.Extractors{
+2 -2
View File
@@ -27,8 +27,8 @@ func TestExtractors_OverridesFollowTheBrowserNotTheDirectory(t *testing.T) {
yandex, ok := browser.Lookup("yandex")
require.True(t, ok)
extractors := Extractors(browser.UserDataDir{ID: "yandex-2", Browser: yandex}, browser.Profile{})
assert.Equal(t, "Ya Passman Data", extractors[category.Password].Sources[0].Path)
assert.Equal(t, "Ya Credit Cards", extractors[category.CreditCard].Sources[0].Path)
assert.Equal(t, "Ya Passman Data", extractors[category.Password].Sources[0].RelativePath)
assert.Equal(t, "Ya Credit Cards", extractors[category.CreditCard].Sources[0].RelativePath)
}
// TestExtractors_EachProfileReadsItsOwnFiles reads one snapshot shared by every profile; each must get its own files.
+1 -1
View File
@@ -60,7 +60,7 @@ func TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind(t *testing.T) {
dir, err := DiscoverAt(nightly, "chromium-yandex", "nightly", t.TempDir())
require.NoError(t, err)
assert.Equal(t, nightly, dir.Browser)
assert.Equal(t, "Ya Passman Data", Extractors(dir, browser.Profile{})[category.Password].Sources[0].Path)
assert.Equal(t, "Ya Passman Data", Extractors(dir, browser.Profile{})[category.Password].Sources[0].RelativePath)
_, err = DiscoverAt(nightly, "bogus", "nightly", t.TempDir())
require.Error(t, err)
+1 -1
View File
@@ -184,7 +184,7 @@ func insertCreditCard(name string, month, year int, encNumberHex, nickName, addr
}
func testBrowser(name string, userDataDirs ...string) browser.Browser {
platform := browser.Platform{UserDataDirs: userDataDirs, SecretLabel: "Test Safe Storage"}
platform := browser.Platform{UserDataDirPaths: userDataDirs, SecretLabel: "Test Safe Storage"}
return browser.Browser{Name: name, DisplayName: name, Base: browser.Chromium, Darwin: platform, Linux: platform, Windows: platform}
}
+11 -11
View File
@@ -17,21 +17,21 @@ import (
// Source is one file or directory an extractor reads.
type Source struct {
Path string // slash-separated, relative to the profile dir, or to the user data dir when Shared
Fallbacks []string // older locations, read only when Path is absent
IsDir bool
Shared bool // belongs to the whole user data dir, such as Local State, so it is captured once per dir
Optional bool // the extraction still runs without it
RelativePath string // slash-separated, relative to the profile dir, or to the user data dir when Shared
Fallbacks []string // older locations, read only when RelativePath is absent
IsDir bool
Shared bool // belongs to the whole user data dir, such as Local State, so it is captured once per dir
Optional bool // the extraction still runs without it
}
// Paths lists Path and then its Fallbacks, the order they are tried in.
func (s Source) Paths() []string {
return append([]string{s.Path}, s.Fallbacks...)
// RelativePaths lists RelativePath and then its Fallbacks, the order they are tried in.
func (s Source) RelativePaths() []string {
return append([]string{s.RelativePath}, s.Fallbacks...)
}
// CandidatePaths are the Paths for a profile, relative to the user data dir.
// CandidatePaths are the RelativePaths for a profile, relative to the user data dir.
func (s Source) CandidatePaths(profile Profile) []string {
paths := s.Paths()
paths := s.RelativePaths()
if !s.Shared {
for i, relativePath := range paths {
paths[i] = path.Join(profile.RelativePath, relativePath)
@@ -84,7 +84,7 @@ func (in Input) Path(source Source) (string, error) {
}
return capturedPath, err
}
return "", fmt.Errorf("%s: %w", strings.Join(source.Paths(), " or "), fs.ErrNotExist)
return "", fmt.Errorf("%s: %w", strings.Join(source.RelativePaths(), " or "), fs.ErrNotExist)
}
// MasterKeys may block on its first call; a key version that could not be retrieved is absent from the Set.
+9 -9
View File
@@ -29,15 +29,15 @@ func TestInputPath(t *testing.T) {
dirSnapshot := snapshot.Open(root).Snapshot("chrome")
input := NewInput(dirSnapshot, Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
got, err := input.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}})
got, err := input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}})
require.NoError(t, err)
assert.Equal(t, legacyCookies, got, "a candidate that was never captured is skipped")
got, err = input.Path(Source{Path: "Local State", Shared: true})
got, err = input.Path(Source{RelativePath: "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 = input.Path(Source{Path: "History"})
_, err = input.Path(Source{RelativePath: "History"})
require.ErrorIs(t, err, fs.ErrNotExist)
}
@@ -46,7 +46,7 @@ func TestInputPath_FlatLayoutProfile(t *testing.T) {
history := writeSnapshotFile(t, root, "opera/History")
input := NewInput(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil, nil)
got, err := input.Path(Source{Path: "History"})
got, err := input.Path(Source{RelativePath: "History"})
require.NoError(t, err)
assert.Equal(t, history, got)
}
@@ -57,7 +57,7 @@ func TestInputPath_FailedCopyIsReported(t *testing.T) {
require.NoError(t, os.MkdirAll(filepath.Join(from, "Default", "Network", "Cookies"), 0o700))
writeSnapshotFile(t, from, "Default/Cookies")
root, err := snapshot.Temp()
root, err := snapshot.NewRoot()
require.NoError(t, err)
defer func() { require.NoError(t, root.Close()) }()
require.NoError(t, root.Capture(context.Background(), []snapshot.File{
@@ -66,7 +66,7 @@ func TestInputPath_FailedCopyIsReported(t *testing.T) {
}))
input := NewInput(root.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
_, err = input.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}})
_, err = input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}})
require.Error(t, err)
assert.NotErrorIs(t, err, fs.ErrNotExist)
}
@@ -87,8 +87,8 @@ func TestInputMasterKeys(t *testing.T) {
func TestSourceCandidatePaths(t *testing.T) {
profile := Profile{Name: "Default", RelativePath: "Default"}
assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}.CandidatePaths(profile))
assert.Equal(t, []string{"Local State"}, Source{Path: "Local State", Shared: true}.CandidatePaths(profile))
assert.Equal(t, []string{"History"}, Source{Path: "History"}.CandidatePaths(Profile{Name: "default"}),
assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}.CandidatePaths(profile))
assert.Equal(t, []string{"Local State"}, Source{RelativePath: "Local State", Shared: true}.CandidatePaths(profile))
assert.Equal(t, []string{"History"}, Source{RelativePath: "History"}.CandidatePaths(Profile{Name: "default"}),
"a user data dir that is itself the profile")
}
+9 -9
View File
@@ -14,12 +14,12 @@ import (
)
var (
loginsJSON = browser.Source{Path: "logins.json"}
keyStore = browser.Source{Path: "key4.db", Optional: true}
placesDB = browser.Source{Path: "places.sqlite"}
cookiesDB = browser.Source{Path: "cookies.sqlite"}
extensionsJSON = browser.Source{Path: "extensions.json"}
webappsStore = browser.Source{Path: "webappsstore.sqlite"}
loginsJSON = browser.Source{RelativePath: "logins.json"}
keyStore = browser.Source{RelativePath: "key4.db", Optional: true}
placesDB = browser.Source{RelativePath: "places.sqlite"}
cookiesDB = browser.Source{RelativePath: "cookies.sqlite"}
extensionsJSON = browser.Source{RelativePath: "extensions.json"}
webappsStore = browser.Source{RelativePath: "webappsstore.sqlite"}
)
// defaultExtractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads.
@@ -71,8 +71,8 @@ func profileAt(firefoxBrowser browser.Browser, path string) []browser.UserDataDi
}
func userDataDirPaths(firefoxBrowser browser.Browser, options browser.DiscoverOptions) []string {
paths := make([]string, 0, len(firefoxBrowser.Platform().UserDataDirs))
for _, relativePath := range firefoxBrowser.Platform().UserDataDirs {
paths := make([]string, 0, len(firefoxBrowser.Platform().UserDataDirPaths))
for _, relativePath := range firefoxBrowser.Platform().UserDataDirPaths {
paths = append(paths, filepath.Join(options.HomeDir, filepath.FromSlash(relativePath)))
}
return paths
@@ -99,7 +99,7 @@ func hasDataFile(path string) bool {
if source.Optional {
continue
}
for _, relativePath := range source.Paths() {
for _, relativePath := range source.RelativePaths() {
if _, err := os.Stat(filepath.Join(path, filepath.FromSlash(relativePath))); err == nil {
return true
}
+1 -1
View File
@@ -19,7 +19,7 @@ import (
)
func testBrowser(userDataDirs ...string) browser.Browser {
platform := browser.Platform{UserDataDirs: userDataDirs}
platform := browser.Platform{UserDataDirPaths: userDataDirs}
return browser.Browser{Name: "firefox", DisplayName: "Firefox", Base: browser.Firefox, Darwin: platform, Linux: platform, Windows: platform}
}
+1 -1
View File
@@ -39,7 +39,7 @@ func namedProfiles(ctx context.Context, library string, id browser.UserDataDirID
// readNamedProfilesFromDB reads a copy, never Safari's live file; (nil, err) means unreadable, and any slice is final.
func readNamedProfilesFromDB(ctx context.Context, library string, id browser.UserDataDirID) ([]browser.Profile, error) {
root, err := snapshot.Temp()
root, err := snapshot.NewRoot()
if err != nil {
return nil, err
}
+1 -1
View File
@@ -15,7 +15,7 @@ import (
)
func testBrowser() browser.Browser {
platform := browser.Platform{UserDataDirs: []string{"Library/Safari"}}
platform := browser.Platform{UserDataDirPaths: []string{"Library/Safari"}}
return browser.Browser{Name: "safari", DisplayName: "Safari", Base: browser.Safari, Darwin: platform, Linux: platform, Windows: platform}
}
+14 -14
View File
@@ -50,8 +50,8 @@ func userDataDirPaths(safariBrowser browser.Browser, options browser.DiscoverOpt
if options.ProfilePath != "" {
return []string{filepath.Clean(options.ProfilePath)}
}
paths := make([]string, 0, len(safariBrowser.Platform().UserDataDirs))
for _, relativePath := range safariBrowser.Platform().UserDataDirs {
paths := make([]string, 0, len(safariBrowser.Platform().UserDataDirPaths))
for _, relativePath := range safariBrowser.Platform().UserDataDirPaths {
paths = append(paths, filepath.Join(options.HomeDir, filepath.FromSlash(relativePath)))
}
return paths
@@ -68,16 +68,16 @@ func Extractors(dir browser.UserDataDir, profile browser.Profile) browser.Extrac
func defaultProfileExtractors(profile browser.Profile) browser.Extractors {
var (
history = browser.Source{Path: "History.db"}
history = browser.Source{RelativePath: "History.db"}
cookies = browser.Source{
Path: fromLibrary(profile, containerDir+"/Cookies/Cookies.binarycookies"),
Fallbacks: []string{fromLibrary(profile, "Cookies/Cookies.binarycookies")},
RelativePath: fromLibrary(profile, containerDir+"/Cookies/Cookies.binarycookies"),
Fallbacks: []string{fromLibrary(profile, "Cookies/Cookies.binarycookies")},
}
bookmarks = browser.Source{Path: "Bookmarks.plist"}
downloads = browser.Source{Path: "Downloads.plist"}
localStorage = browser.Source{Path: fromLibrary(profile, containerDir+"/WebKit/WebsiteData/Default"), IsDir: true}
appExtensions = browser.Source{Path: fromLibrary(profile, containerDir+"/Safari/AppExtensions/Extensions.plist"), Optional: true}
webExtensions = browser.Source{Path: fromLibrary(profile, containerDir+"/Safari/WebExtensions/Extensions.plist"), Optional: true}
bookmarks = browser.Source{RelativePath: "Bookmarks.plist"}
downloads = browser.Source{RelativePath: "Downloads.plist"}
localStorage = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/WebKit/WebsiteData/Default"), IsDir: true}
appExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/AppExtensions/Extensions.plist"), Optional: true}
webExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/WebExtensions/Extensions.plist"), Optional: true}
)
return browser.Extractors{
category.Password: {Extract: extractPasswords},
@@ -93,10 +93,10 @@ func defaultProfileExtractors(profile browser.Profile) browser.Extractors {
func namedProfileExtractors(dir browser.UserDataDir, profile browser.Profile, uuid string) browser.Extractors {
store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(uuid)
var (
history = browser.Source{Path: "History.db"}
cookies = browser.Source{Path: fromLibrary(profile, store+"/Cookies/Cookies.binarycookies")}
downloads = browser.Source{Path: fromLibrary(profile, defaultProfileDir(dir)+"/Downloads.plist")}
localStorage = browser.Source{Path: fromLibrary(profile, store+"/Origins"), IsDir: true}
history = browser.Source{RelativePath: "History.db"}
cookies = browser.Source{RelativePath: fromLibrary(profile, store+"/Cookies/Cookies.binarycookies")}
downloads = browser.Source{RelativePath: fromLibrary(profile, defaultProfileDir(dir)+"/Downloads.plist")}
localStorage = browser.Source{RelativePath: fromLibrary(profile, store+"/Origins"), IsDir: true}
)
return browser.Extractors{
category.History: newPlainExtractor(extractHistories, history),
+1 -1
View File
@@ -32,7 +32,7 @@ func sourcePaths(profile browser.Profile, extractors browser.Extractors) map[cat
got := make(map[category.Category][]string, len(extractors))
for dataCategory, extractor := range extractors {
for _, source := range extractor.Sources {
for _, relativePath := range source.Paths() {
for _, relativePath := range source.RelativePaths() {
got[dataCategory] = append(got[dataCategory], path.Join(profile.RelativePath, relativePath))
}
}
+67 -67
View File
@@ -9,17 +9,17 @@ var browsers = []Browser{
DisplayName: "Chrome",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Google/Chrome"},
SecretLabel: "Chrome",
UserDataDirPaths: []string{"Library/Application Support/Google/Chrome"},
SecretLabel: "Chrome",
},
Linux: Platform{
UserDataDirs: []string{".config/google-chrome"},
SecretLabel: "Chrome Safe Storage",
PortalAppID: "com.google.Chrome",
UserDataDirPaths: []string{".config/google-chrome"},
SecretLabel: "Chrome Safe Storage",
PortalAppID: "com.google.Chrome",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Google/Chrome/User Data"},
Executable: "chrome.exe",
UserDataDirPaths: []string{"AppData/Local/Google/Chrome/User Data"},
Executable: "chrome.exe",
ExecutableFallbacks: []string{
`%ProgramFiles%\Google\Chrome\Application\chrome.exe`,
`%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`,
@@ -33,16 +33,16 @@ var browsers = []Browser{
DisplayName: "Microsoft Edge",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Microsoft Edge"},
SecretLabel: "Microsoft Edge",
UserDataDirPaths: []string{"Library/Application Support/Microsoft Edge"},
SecretLabel: "Microsoft Edge",
},
Linux: Platform{
UserDataDirs: []string{".config/microsoft-edge"},
SecretLabel: "Chromium Safe Storage",
UserDataDirPaths: []string{".config/microsoft-edge"},
SecretLabel: "Chromium Safe Storage",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Microsoft/Edge/User Data"},
Executable: "msedge.exe",
UserDataDirPaths: []string{"AppData/Local/Microsoft/Edge/User Data"},
Executable: "msedge.exe",
ExecutableFallbacks: []string{
`%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`,
`%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`,
@@ -55,16 +55,16 @@ var browsers = []Browser{
DisplayName: "Chromium",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Chromium"},
SecretLabel: "Chromium",
UserDataDirPaths: []string{"Library/Application Support/Chromium"},
SecretLabel: "Chromium",
},
Linux: Platform{
UserDataDirs: []string{".config/chromium"},
SecretLabel: "Chromium Safe Storage",
PortalAppID: "org.chromium.Chromium",
UserDataDirPaths: []string{".config/chromium"},
SecretLabel: "Chromium Safe Storage",
PortalAppID: "org.chromium.Chromium",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Chromium/User Data"},
UserDataDirPaths: []string{"AppData/Local/Chromium/User Data"},
},
},
{
@@ -72,17 +72,17 @@ var browsers = []Browser{
DisplayName: "Chrome Beta",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Google/Chrome Beta"},
SecretLabel: "Chrome",
UserDataDirPaths: []string{"Library/Application Support/Google/Chrome Beta"},
SecretLabel: "Chrome",
},
Linux: Platform{
UserDataDirs: []string{".config/google-chrome-beta"},
SecretLabel: "Chrome Safe Storage",
PortalAppID: "com.google.Chrome.beta",
UserDataDirPaths: []string{".config/google-chrome-beta"},
SecretLabel: "Chrome Safe Storage",
PortalAppID: "com.google.Chrome.beta",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Google/Chrome Beta/User Data"},
Executable: "chrome.exe",
UserDataDirPaths: []string{"AppData/Local/Google/Chrome Beta/User Data"},
Executable: "chrome.exe",
ExecutableFallbacks: []string{
`%ProgramFiles%\Google\Chrome Beta\Application\chrome.exe`,
`%ProgramFiles(x86)%\Google\Chrome Beta\Application\chrome.exe`,
@@ -96,15 +96,15 @@ var browsers = []Browser{
DisplayName: "Opera",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/com.operasoftware.Opera"},
SecretLabel: "Opera",
UserDataDirPaths: []string{"Library/Application Support/com.operasoftware.Opera"},
SecretLabel: "Opera",
},
Linux: Platform{
UserDataDirs: []string{".config/opera"},
SecretLabel: "Chromium Safe Storage",
UserDataDirPaths: []string{".config/opera"},
SecretLabel: "Chromium Safe Storage",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Roaming/Opera Software/Opera Stable"},
UserDataDirPaths: []string{"AppData/Roaming/Opera Software/Opera Stable"},
},
},
{
@@ -112,11 +112,11 @@ var browsers = []Browser{
DisplayName: "OperaGX",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/com.operasoftware.OperaGX"},
SecretLabel: "Opera",
UserDataDirPaths: []string{"Library/Application Support/com.operasoftware.OperaGX"},
SecretLabel: "Opera",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Roaming/Opera Software/Opera GX Stable"},
UserDataDirPaths: []string{"AppData/Roaming/Opera Software/Opera GX Stable"},
},
},
{
@@ -124,7 +124,7 @@ var browsers = []Browser{
DisplayName: "Browser from Vought",
Base: Chromium,
Windows: Platform{
UserDataDirs: []string{"AppData/Roaming/Browser from Vought"},
UserDataDirPaths: []string{"AppData/Roaming/Browser from Vought"},
},
},
{
@@ -132,15 +132,15 @@ var browsers = []Browser{
DisplayName: "Vivaldi",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Vivaldi"},
SecretLabel: "Vivaldi",
UserDataDirPaths: []string{"Library/Application Support/Vivaldi"},
SecretLabel: "Vivaldi",
},
Linux: Platform{
UserDataDirs: []string{".config/vivaldi"},
SecretLabel: "Chrome Safe Storage",
UserDataDirPaths: []string{".config/vivaldi"},
SecretLabel: "Chrome Safe Storage",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Vivaldi/User Data"},
UserDataDirPaths: []string{"AppData/Local/Vivaldi/User Data"},
},
},
{
@@ -148,12 +148,12 @@ var browsers = []Browser{
DisplayName: "CocCoc",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Coccoc"},
SecretLabel: "CocCoc",
UserDataDirPaths: []string{"Library/Application Support/Coccoc"},
SecretLabel: "CocCoc",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/CocCoc/Browser/User Data"},
Executable: "browser.exe",
UserDataDirPaths: []string{"AppData/Local/CocCoc/Browser/User Data"},
Executable: "browser.exe",
ExecutableFallbacks: []string{
`%ProgramFiles%\CocCoc\Browser\Application\browser.exe`,
`%ProgramFiles(x86)%\CocCoc\Browser\Application\browser.exe`,
@@ -167,17 +167,17 @@ var browsers = []Browser{
DisplayName: "Brave",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/BraveSoftware/Brave-Browser"},
SecretLabel: "Brave",
UserDataDirPaths: []string{"Library/Application Support/BraveSoftware/Brave-Browser"},
SecretLabel: "Brave",
},
Linux: Platform{
UserDataDirs: []string{".config/BraveSoftware/Brave-Browser"},
SecretLabel: "Brave Safe Storage",
PortalAppID: "com.brave.Browser",
UserDataDirPaths: []string{".config/BraveSoftware/Brave-Browser"},
SecretLabel: "Brave Safe Storage",
PortalAppID: "com.brave.Browser",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/BraveSoftware/Brave-Browser/User Data"},
Executable: "brave.exe",
UserDataDirPaths: []string{"AppData/Local/BraveSoftware/Brave-Browser/User Data"},
Executable: "brave.exe",
ExecutableFallbacks: []string{
`%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`,
`%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`,
@@ -191,11 +191,11 @@ var browsers = []Browser{
DisplayName: "Yandex",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Yandex/YandexBrowser"},
SecretLabel: "Yandex",
UserDataDirPaths: []string{"Library/Application Support/Yandex/YandexBrowser"},
SecretLabel: "Yandex",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Yandex/YandexBrowser/User Data"},
UserDataDirPaths: []string{"AppData/Local/Yandex/YandexBrowser/User Data"},
},
},
{
@@ -203,7 +203,7 @@ var browsers = []Browser{
DisplayName: "360 Speed X",
Base: Chromium,
Windows: Platform{
UserDataDirs: []string{"AppData/Local/360ChromeX/Chrome/User Data"},
UserDataDirPaths: []string{"AppData/Local/360ChromeX/Chrome/User Data"},
},
},
{
@@ -211,7 +211,7 @@ var browsers = []Browser{
DisplayName: "360 Speed",
Base: Chromium,
Windows: Platform{
UserDataDirs: []string{"AppData/Local/360chrome/Chrome/User Data"},
UserDataDirPaths: []string{"AppData/Local/360chrome/Chrome/User Data"},
},
},
{
@@ -219,7 +219,7 @@ var browsers = []Browser{
DisplayName: "QQ",
Base: Chromium,
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Tencent/QQBrowser/User Data"},
UserDataDirPaths: []string{"AppData/Local/Tencent/QQBrowser/User Data"},
},
},
{
@@ -227,7 +227,7 @@ var browsers = []Browser{
DisplayName: "DC",
Base: Chromium,
Windows: Platform{
UserDataDirs: []string{"AppData/Local/DCBrowser/User Data"},
UserDataDirPaths: []string{"AppData/Local/DCBrowser/User Data"},
},
},
{
@@ -235,7 +235,7 @@ var browsers = []Browser{
DisplayName: "Sogou",
Base: Chromium,
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Sogou/SogouExplorer/User Data"},
UserDataDirPaths: []string{"AppData/Local/Sogou/SogouExplorer/User Data"},
},
},
{
@@ -243,11 +243,11 @@ var browsers = []Browser{
DisplayName: "Arc",
Base: Chromium,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Arc/User Data"},
SecretLabel: "Arc",
UserDataDirPaths: []string{"Library/Application Support/Arc/User Data"},
SecretLabel: "Arc",
},
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Packages/TheBrowserCompany.Arc_*/LocalCache/Local/Arc/User Data"},
UserDataDirPaths: []string{"AppData/Local/Packages/TheBrowserCompany.Arc_*/LocalCache/Local/Arc/User Data"},
},
},
{
@@ -255,7 +255,7 @@ var browsers = []Browser{
DisplayName: "DuckDuckGo",
Base: Chromium,
Windows: Platform{
UserDataDirs: []string{"AppData/Local/Packages/DuckDuckGo.DesktopBrowser_*/LocalState/EBWebView"},
UserDataDirPaths: []string{"AppData/Local/Packages/DuckDuckGo.DesktopBrowser_*/LocalState/EBWebView"},
},
},
{
@@ -263,13 +263,13 @@ var browsers = []Browser{
DisplayName: "Firefox",
Base: Firefox,
Darwin: Platform{
UserDataDirs: []string{"Library/Application Support/Firefox/Profiles"},
UserDataDirPaths: []string{"Library/Application Support/Firefox/Profiles"},
},
Linux: Platform{
UserDataDirs: []string{".mozilla/firefox"},
UserDataDirPaths: []string{".mozilla/firefox"},
},
Windows: Platform{
UserDataDirs: []string{"AppData/Roaming/Mozilla/Firefox/Profiles"},
UserDataDirPaths: []string{"AppData/Roaming/Mozilla/Firefox/Profiles"},
},
},
{
@@ -277,7 +277,7 @@ var browsers = []Browser{
DisplayName: "Safari",
Base: Safari,
Darwin: Platform{
UserDataDirs: []string{"Library/Safari"},
UserDataDirPaths: []string{"Library/Safari"},
},
},
}
+1 -1
View File
@@ -41,7 +41,7 @@ func TestTableRows(t *testing.T) {
assert.Contains(t, []Base{Chromium, Firefox, Safari}, browser.Base, browser.Name)
for goos, platform := range platformOf {
for _, dir := range platform(browser).UserDataDirs {
for _, dir := range platform(browser).UserDataDirPaths {
assert.Truef(t, dir != "" && !path.IsAbs(dir) && !strings.Contains(dir, `\`),
"%s %s: user data dir %q must be slash-separated and relative to the home dir", browser.Name, goos, dir)
}
+4 -4
View File
@@ -42,12 +42,12 @@ type categoryFile struct {
count int
}
// NewWriter creates dir. With zip, Close packs the files it wrote into <dir>/<base of dir>.zip.
func NewWriter(dir string, format Format, zip bool) (*Writer, error) {
if err := os.MkdirAll(dir, 0o750); err != nil {
// NewWriter creates outputDir. With zip, Close packs the files it wrote into <outputDir>/<base of outputDir>.zip.
func NewWriter(outputDir string, format Format, zip bool) (*Writer, error) {
if err := os.MkdirAll(outputDir, 0o750); err != nil {
return nil, fmt.Errorf("create output dir: %w", err)
}
return &Writer{dir: dir, format: format, zip: zip, files: make(map[category.Category]*categoryFile)}, nil
return &Writer{dir: outputDir, format: format, zip: zip, files: make(map[category.Category]*categoryFile)}, nil
}
// Write reorders records in place.
+3 -3
View File
@@ -26,8 +26,8 @@ type Root struct {
failed map[string]error // keyed by the cleaned <UserDataDirID>/<RelativePath>, so any spelling of a file finds its failure
}
// Temp creates a private temporary snapshot directory, which Close removes.
func Temp() (*Root, error) {
// NewRoot creates a private temporary snapshot directory, which Close removes.
func NewRoot() (*Root, error) {
path, err := os.MkdirTemp("", "hbd-snapshot-*")
if err != nil {
return nil, fmt.Errorf("create snapshot dir: %w", err)
@@ -42,7 +42,7 @@ func Open(path string) *Root {
// Unzip extracts an archive into a temporary snapshot directory, rejecting entries that would land outside it.
func Unzip(archivePath string) (*Root, error) {
root, err := Temp()
root, err := NewRoot()
if err != nil {
return nil, err
}
+7 -7
View File
@@ -32,7 +32,7 @@ func userDataDir(t *testing.T) string {
}
func TestTemp_IsPrivateAndCloseRemovesIt(t *testing.T) {
root, err := Temp()
root, err := NewRoot()
require.NoError(t, err)
info, err := os.Stat(root.Path())
require.NoError(t, err)
@@ -59,7 +59,7 @@ func TestOpen_ReadsInPlaceAndCloseLeavesIt(t *testing.T) {
func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) {
from := userDataDir(t)
root, err := Temp()
root, err := NewRoot()
require.NoError(t, err)
defer root.Close()
@@ -88,7 +88,7 @@ func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) {
func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) {
from := userDataDir(t)
root, err := Temp()
root, err := NewRoot()
require.NoError(t, err)
defer root.Close()
@@ -112,7 +112,7 @@ func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) {
func TestCapture_StopsWhenCancelled(t *testing.T) {
from := userDataDir(t)
root, err := Temp()
root, err := NewRoot()
require.NoError(t, err)
defer root.Close()
@@ -127,7 +127,7 @@ func TestCapture_StopsWhenCancelled(t *testing.T) {
func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) {
from := userDataDir(t)
root, err := Temp()
root, err := NewRoot()
require.NoError(t, err)
defer root.Close()
@@ -147,7 +147,7 @@ func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) {
}
func TestSnapshot_UncapturedFileIsNotExist(t *testing.T) {
root, err := Temp()
root, err := NewRoot()
require.NoError(t, err)
defer root.Close()
@@ -157,7 +157,7 @@ func TestSnapshot_UncapturedFileIsNotExist(t *testing.T) {
func TestCapture_ALaterCaptureReplacesAnEarlierFailure(t *testing.T) {
from := t.TempDir()
root, err := Temp()
root, err := NewRoot()
require.NoError(t, err)
defer root.Close()
+3 -3
View File
@@ -42,8 +42,8 @@ func addFile(zipWriter *zip.Writer, path, name string) error {
return err
}
// Extract unpacks archivePath into dir, refusing any entry that would land outside it.
func Extract(archivePath, dir string) error {
// Extract unpacks archivePath into targetDir, refusing any entry that would land outside it.
func Extract(archivePath, targetDir string) error {
zipReader, err := zip.OpenReader(archivePath)
if err != nil {
return fmt.Errorf("open zip %s: %w", archivePath, err)
@@ -55,7 +55,7 @@ func Extract(archivePath, dir string) error {
if !filepath.IsLocal(name) {
return fmt.Errorf("zip entry %q escapes destination", zipFile.Name)
}
target := filepath.Join(dir, name)
target := filepath.Join(targetDir, name)
if zipFile.FileInfo().IsDir() {
if err := os.MkdirAll(target, 0o700); err != nil {
return err
+2
View File
@@ -37,5 +37,7 @@ Dependencies point down only. Interfaces live with their consumer, nothing regis
- Names are spelled out; only Go's universal idioms stay short, and lint enforces it.
- The domain's words: a **browser** is a row of the browser table; its **base** is what it is built on (Chromium, Firefox, or Safari); a **user data dir** is a browser's data directory, where an installation would be the program; and a **profile**, an **extraction**, a **snapshot**, a **record**, and a **category** mean what they say.
- Unqualified, "dir" means a user data dir; any other directory is named for what it holds.
- A field named for a thing holds the thing itself; one that holds only its name or its path says so, unless it mirrors a name in the output or the keys file.
- A path is absolute unless its name says it is relative.
**Rejected:** "engine" for the base, which means the renderer; "origin" or "owner" for where a record came from, which are web and access-control terms; and "job" for an extraction, which suggests a worker pool that does not exist.