mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
refactor: pass secrets as values, fetched once per scope (#713)
* refactor: pass secrets as values, fetched once per scope A master key travelled through five layers of function values and three sync.Once guarded reuse; holding each secret where its scope lives shows where it comes from. Only the keychain prompt still waits for first use. * docs(rfcs): fetch secrets per extraction, not per record
This commit is contained in:
1 parent
a734e777a8
commit
f36790d4dd
41 files changed
+285
-388
No files matched your search
@@ -42,10 +42,13 @@ func newDumpCommand() *cobra.Command {
|
||||
}
|
||||
|
||||
func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychain, firefox passwordFlags) error {
|
||||
options, err := app.ValidateDump(flags, keychainPasswordFunc(keychain, os.Stdin), firefoxPasswordFunc(firefox, os.Stdin))
|
||||
options, err := app.ValidateDump(flags, keychainPasswordFunc(keychain, os.Stdin))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if options.FirefoxPrimaryPassword, err = readFirefoxPassword(ctx, firefox, os.Stdin); err != nil {
|
||||
return err
|
||||
}
|
||||
discovery, summary, err := app.Dump(ctx, options)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/keychain"
|
||||
)
|
||||
|
||||
// passwordFlags say where one password comes from: its flag, or the first line of stdin. Neither leaves it to the
|
||||
@@ -27,25 +29,18 @@ func addPasswordFlags(command *cobra.Command, flags *passwordFlags, name, what s
|
||||
command.MarkFlagsMutuallyExclusive(name, name+"-stdin")
|
||||
}
|
||||
|
||||
// firefoxPasswordFunc reads a flag, else the first line of stdin; nil means the empty password, and it never prompts.
|
||||
func firefoxPasswordFunc(flags passwordFlags, stdin *os.File) func(context.Context) (string, error) {
|
||||
switch {
|
||||
case flags.value != "":
|
||||
password := flags.value
|
||||
return func(context.Context) (string, error) { return password, nil }
|
||||
case flags.fromStdin:
|
||||
return func(ctx context.Context) (string, error) {
|
||||
return untilDone(ctx, func() (string, error) { return firstLine(stdin) })
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
// readFirefoxPassword takes the flag, else the first line of stdin; "" is the empty password, and it never prompts.
|
||||
func readFirefoxPassword(ctx context.Context, flags passwordFlags, stdin io.Reader) (string, error) {
|
||||
if flags.fromStdin {
|
||||
return untilDone(ctx, func() (string, error) { return firstLine(stdin) })
|
||||
}
|
||||
return flags.value, nil
|
||||
}
|
||||
|
||||
var errNoPassword = errors.New("macOS login password not given and stdin is not a terminal")
|
||||
|
||||
// keychainPasswordFunc is read lazily: a flag, else a no-echo prompt on a terminal, else none (metadata only).
|
||||
func keychainPasswordFunc(flags passwordFlags, stdin *os.File) func(context.Context) (string, error) {
|
||||
func keychainPasswordFunc(flags passwordFlags, stdin *os.File) keychain.PasswordFunc {
|
||||
switch {
|
||||
case flags.value != "":
|
||||
password := flags.value
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/firefox"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/safari"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
)
|
||||
|
||||
// Discovery keeps a failure per browser whose data could not be read, so it is reported, not taken as absence.
|
||||
@@ -85,3 +86,8 @@ func extractorsFor(dir browser.UserDataDir, profile browser.Profile) browser.Ext
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// needsMasterKeys dispatches on Base for the same reason; Chromium is the one base whose dir holds master keys.
|
||||
func needsMasterKeys(dir browser.UserDataDir, dataCategory category.Category) bool {
|
||||
return dir.Browser.Base == browser.Chromium && chromium.NeedsMasterKeys(dataCategory)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/keychain"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
)
|
||||
|
||||
@@ -25,12 +26,13 @@ type DumpOptions struct {
|
||||
Categories []category.Category
|
||||
Output OutputOptions
|
||||
// KeychainPassword runs when the macOS login keychain first opens; "" leaves it locked. Other systems ignore it.
|
||||
KeychainPassword func(ctx context.Context) (string, error)
|
||||
FirefoxPassword func(ctx context.Context) (string, error) // nil is the empty password; Dump reads it at most once
|
||||
KeychainPassword keychain.PasswordFunc
|
||||
// FirefoxPrimaryPassword is set by the caller once ValidateDump passes, so a bad flag never consumes stdin.
|
||||
FirefoxPrimaryPassword string
|
||||
}
|
||||
|
||||
// ValidateDump checks every flag before any browser or secret is touched, so a bad flag fails fast.
|
||||
func ValidateDump(flags DumpFlags, keychainPassword, firefoxPassword func(context.Context) (string, error)) (DumpOptions, error) {
|
||||
func ValidateDump(flags DumpFlags, keychainPassword keychain.PasswordFunc) (DumpOptions, error) {
|
||||
browsers, err := parseBrowsers(flags.Browser)
|
||||
if err != nil {
|
||||
return DumpOptions{}, err
|
||||
@@ -58,7 +60,6 @@ func ValidateDump(flags DumpFlags, keychainPassword, firefoxPassword func(contex
|
||||
Categories: categories,
|
||||
Output: output,
|
||||
KeychainPassword: keychainPassword,
|
||||
FirefoxPassword: firefoxPassword,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -88,14 +89,15 @@ func Dump(ctx context.Context, options DumpOptions) (Discovery, Summary, error)
|
||||
if len(discovery.Dirs) == 0 {
|
||||
return discovery, Summary{}, nil
|
||||
}
|
||||
keychain := newLoginKeychain(loginKeychainPath(options.HomeDir), options.KeychainPassword)
|
||||
loginKeychain := newLoginKeychain(loginKeychainPath(options.HomeDir), options.KeychainPassword)
|
||||
fromMachine := runner{
|
||||
extractors: extractorsFor, retrieveKeys: keysFromMachine(keychain), loginKeychain: keychain,
|
||||
firefoxPassword: readOnce(options.FirefoxPassword),
|
||||
extractors: extractorsFor, keySource: machineKeys{loginKeychain: loginKeychain}, loginKeychain: loginKeychain,
|
||||
firefoxPrimaryPassword: options.FirefoxPrimaryPassword,
|
||||
}
|
||||
summary, err := execute(ctx, discovery, options.Categories, options.Output, fromMachine)
|
||||
if err != nil {
|
||||
return Discovery{}, Summary{}, err
|
||||
}
|
||||
warnIfLocked(ctx, loginKeychain, "keychain-protected data was exported as metadata only")
|
||||
return discovery, summary, nil
|
||||
}
|
||||
@@ -18,9 +18,8 @@ import (
|
||||
|
||||
func TestValidateDump(t *testing.T) {
|
||||
keychainPassword := func(context.Context) (string, error) { return "pw", nil }
|
||||
firefoxPassword := func(context.Context) (string, error) { return "ff", nil }
|
||||
options, err := ValidateDump(DumpFlags{Browser: " Chrome ", Categories: "cookie, password,cookie", Output: OutputFlags{Format: "csv", Dir: "out"}},
|
||||
keychainPassword, firefoxPassword)
|
||||
keychainPassword)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, options.Browsers, 1)
|
||||
assert.Equal(t, "chrome", options.Browsers[0].Name)
|
||||
@@ -31,11 +30,8 @@ func TestValidateDump(t *testing.T) {
|
||||
password, err := options.KeychainPassword(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "pw", password)
|
||||
password, err = options.FirefoxPassword(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "ff", password)
|
||||
|
||||
options, err = ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json"}}, nil, nil)
|
||||
options, err = ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, browser.Supported(), options.Browsers)
|
||||
assert.Equal(t, category.All(), options.Categories)
|
||||
@@ -56,7 +52,7 @@ func TestValidateDump_RejectsBadInput(t *testing.T) {
|
||||
"missing -p": {Browser: "chrome", Categories: "all", Output: OutputFlags{Format: "json"}, ProfilePath: missing},
|
||||
"-p is a file": {Browser: "chrome", Categories: "all", Output: OutputFlags{Format: "json"}, ProfilePath: file},
|
||||
} {
|
||||
_, err := ValidateDump(flags, nil, nil)
|
||||
_, err := ValidateDump(flags, nil)
|
||||
assert.Error(t, err, name)
|
||||
}
|
||||
}
|
||||
@@ -76,7 +72,7 @@ func otherOSBrowser(t *testing.T) string {
|
||||
|
||||
func TestValidateDump_CreatesNoOutputDir(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
options, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "a", "b")}}, nil, nil)
|
||||
options, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "a", "b")}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, filepath.Join(root, "a", "b"), options.Output.Dir)
|
||||
_, err = os.Stat(filepath.Join(root, "a"))
|
||||
@@ -91,13 +87,13 @@ func TestValidateDump_RejectsAnOutputDirThatCannotBeCreated(t *testing.T) {
|
||||
require.NoError(t, os.Chmod(root, 0o500))
|
||||
defer func() { require.NoError(t, os.Chmod(root, 0o700)) }()
|
||||
|
||||
_, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "results")}}, nil, nil)
|
||||
_, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "results")}}, nil)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
// TestValidateDump_IgnoresProfilePathForAllBrowsers keeps -p without a named browser ignored, as before; it is reported.
|
||||
func TestValidateDump_IgnoresProfilePathForAllBrowsers(t *testing.T) {
|
||||
options, err := ValidateDump(DumpFlags{Browser: "all", Categories: "all", Output: OutputFlags{Format: "json"}, ProfilePath: filepath.Join(t.TempDir(), "missing")}, nil, nil)
|
||||
options, err := ValidateDump(DumpFlags{Browser: "all", Categories: "all", Output: OutputFlags{Format: "json"}, ProfilePath: filepath.Join(t.TempDir(), "missing")}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, options.ProfilePath)
|
||||
}
|
||||
+17
-15
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/moond4rk/hackbrowserdata/internal/atomicfile"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/keychain"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
@@ -24,10 +25,10 @@ type DumpKeysOptions struct {
|
||||
HomeDir string
|
||||
OutputPath string // "" writes the key file to stdout
|
||||
// KeychainPassword runs when the macOS login keychain first opens; "" leaves it locked. Other systems ignore it.
|
||||
KeychainPassword func(ctx context.Context) (string, error)
|
||||
KeychainPassword keychain.PasswordFunc
|
||||
}
|
||||
|
||||
func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword func(context.Context) (string, error)) (DumpKeysOptions, error) {
|
||||
func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword keychain.PasswordFunc) (DumpKeysOptions, error) {
|
||||
browsers, err := parseBrowsers(flags.Browser)
|
||||
if err != nil {
|
||||
return DumpKeysOptions{}, err
|
||||
@@ -48,11 +49,12 @@ func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword func(context.Context
|
||||
// A stopped run writes nothing, so it never leaves a keys.json behind.
|
||||
func DumpKeys(ctx context.Context, options DumpKeysOptions, stdout io.Writer) (int, error) {
|
||||
discovery := discover(ctx, options.Browsers, browser.DiscoverOptions{HomeDir: options.HomeDir})
|
||||
keychain := newLoginKeychain(loginKeychainPath(options.HomeDir), options.KeychainPassword)
|
||||
keyFile, err := dumpKeysWith(ctx, discovery, keysFromMachine(keychain))
|
||||
loginKeychain := newLoginKeychain(loginKeychainPath(options.HomeDir), options.KeychainPassword)
|
||||
keyFile, err := dumpKeysWith(ctx, discovery, machineKeys{loginKeychain: loginKeychain})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
warnIfLocked(ctx, loginKeychain, "keys only it holds are missing from the key file")
|
||||
if options.OutputPath == "" {
|
||||
return len(keyFile.Vaults), keyFile.Write(stdout)
|
||||
}
|
||||
@@ -72,24 +74,24 @@ func writeKeyFile(outputPath string, keyFile masterkey.KeyFile) error {
|
||||
|
||||
// dumpKeysWith keeps the keys that worked when a dir's others fail, and leaves out a dir with none.
|
||||
// It fails only when the run is stopped.
|
||||
func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (masterkey.KeyFile, error) {
|
||||
func dumpKeysWith(ctx context.Context, discovery Discovery, keySource keySource) (masterkey.KeyFile, error) {
|
||||
keyFile := masterkey.NewKeyFile()
|
||||
for _, dir := range discovery.Dirs {
|
||||
if dir.Browser.Base != browser.Chromium {
|
||||
continue
|
||||
}
|
||||
set, err := retrieveDirKeys(ctx, dir, keys)
|
||||
retrieval := retrieveDirKeys(ctx, dir, keySource)
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return masterkey.KeyFile{}, fmt.Errorf("run stopped: %w", ctxErr)
|
||||
}
|
||||
if err != nil {
|
||||
if retrieval.Err != nil {
|
||||
status := "partial"
|
||||
if len(set) == 0 {
|
||||
if len(retrieval.Keys) == 0 {
|
||||
status = "failed"
|
||||
}
|
||||
log.Warnf("dumpkeys: %s %s: %v", dir.Browser.DisplayName, status, err)
|
||||
log.Warnf("dumpkeys: %s %s: %v", dir.Browser.DisplayName, status, retrieval.Err)
|
||||
}
|
||||
if len(set) == 0 {
|
||||
if len(retrieval.Keys) == 0 {
|
||||
continue
|
||||
}
|
||||
vault := masterkey.Vault{
|
||||
@@ -97,7 +99,7 @@ func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (m
|
||||
Kind: chromium.VaultKind(dir.Browser),
|
||||
UserDataDir: dir.Path,
|
||||
Profiles: profileNames(dir),
|
||||
Keys: set,
|
||||
Keys: retrieval.Keys,
|
||||
}
|
||||
if string(dir.ID) != dir.Browser.Name {
|
||||
vault.ID = string(dir.ID)
|
||||
@@ -107,10 +109,10 @@ func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (m
|
||||
return keyFile, nil
|
||||
}
|
||||
|
||||
func retrieveDirKeys(ctx context.Context, dir browser.UserDataDir, keys dirKeysFunc) (masterkey.Set, error) {
|
||||
func retrieveDirKeys(ctx context.Context, dir browser.UserDataDir, keySource keySource) masterkey.Retrieval {
|
||||
root, err := snapshot.NewRoot()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return masterkey.Retrieval{Err: err}
|
||||
}
|
||||
defer closeRoot(root)
|
||||
var files []snapshot.File
|
||||
@@ -120,9 +122,9 @@ func retrieveDirKeys(ctx context.Context, dir browser.UserDataDir, keys dirKeysF
|
||||
}
|
||||
}
|
||||
if err := root.Capture(ctx, files); err != nil {
|
||||
return nil, err
|
||||
return masterkey.Retrieval{Err: err}
|
||||
}
|
||||
return keys(ctx, dir, root.Snapshot(string(dir.ID)))
|
||||
return keySource.MasterKeys(ctx, dir, root.Snapshot(string(dir.ID)))
|
||||
}
|
||||
|
||||
func profileNames(dir browser.UserDataDir) []string {
|
||||
|
||||
@@ -28,20 +28,20 @@ func TestDumpKeysWith(t *testing.T) {
|
||||
arc2, opera, vivaldi, brave := dirOf(t, "arc-2", "arc"), dirOf(t, "opera", "opera"), dirOf(t, "vivaldi", "vivaldi"), dirOf(t, "brave", "brave")
|
||||
firefox := dirOf(t, "firefox", "firefox")
|
||||
|
||||
keys := func(_ context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) {
|
||||
keys := keySourceFunc(func(_ context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval {
|
||||
switch dir.ID {
|
||||
case "chrome":
|
||||
_, err := dirSnapshot.Path("Local State")
|
||||
require.NoError(t, err, "key retrieval reads the captured Local State")
|
||||
case "vivaldi":
|
||||
return nil, errors.New("v10 failed")
|
||||
return masterkey.Retrieval{Err: errors.New("v10 failed")}
|
||||
case "brave":
|
||||
return masterkey.Set{masterkey.V10: []byte("brave")}, errors.New("v20 failed")
|
||||
return masterkey.Retrieval{Keys: masterkey.Set{masterkey.V10: []byte("brave")}, Err: errors.New("v20 failed")}
|
||||
case "firefox":
|
||||
t.Error("Firefox has no keys.json vault")
|
||||
}
|
||||
return masterkey.Set{masterkey.V10: []byte(dir.ID)}, nil
|
||||
}
|
||||
return masterkey.Retrieval{Keys: masterkey.Set{masterkey.V10: []byte(dir.ID)}}
|
||||
})
|
||||
discovery := Discovery{Dirs: []browser.UserDataDir{chrome, firefox, arc2, opera, vivaldi, brave}}
|
||||
keyFile, err := dumpKeysWith(context.Background(), discovery, keys)
|
||||
require.NoError(t, err)
|
||||
@@ -71,11 +71,11 @@ func TestDumpKeysWith_StoppedRunReturnsNoKeyFile(t *testing.T) {
|
||||
defer cancel()
|
||||
chrome, brave := chromeDir(t, "chrome", "Default"), dirOf(t, "brave", "brave")
|
||||
touch(t, chrome.Path, "Local State")
|
||||
keys := func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) {
|
||||
keys := keySourceFunc(func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) masterkey.Retrieval {
|
||||
require.Equal(t, browser.UserDataDirID("chrome"), dir.ID, "keys were retrieved after the stop")
|
||||
cancel()
|
||||
return masterkey.Set{masterkey.V10: []byte("chrome")}, nil
|
||||
}
|
||||
return masterkey.Retrieval{Keys: masterkey.Set{masterkey.V10: []byte("chrome")}}
|
||||
})
|
||||
|
||||
keyFile, err := dumpKeysWith(ctx, Discovery{Dirs: []browser.UserDataDir{chrome, brave}}, keys)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
|
||||
+16
-30
@@ -4,30 +4,16 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/export"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
// readOnce lets every protected Firefox profile of a run share one read, since stdin yields the password only once.
|
||||
func readOnce(read func(context.Context) (string, error)) func(context.Context) (string, error) {
|
||||
if read == nil {
|
||||
return nil
|
||||
}
|
||||
var once sync.Once
|
||||
var password string
|
||||
var err error
|
||||
return func(ctx context.Context) (string, error) {
|
||||
once.Do(func() { password, err = read(ctx) })
|
||||
return password, err
|
||||
}
|
||||
}
|
||||
|
||||
// execute gives the runner the run's writer; the caller sets where its extractors, keys, and keychain come from.
|
||||
// It handles one user data dir at a time, so at most one dir's copies are on disk. Its error means nothing ran.
|
||||
func execute(
|
||||
@@ -51,13 +37,13 @@ type recordWriter interface {
|
||||
|
||||
// runner is what every user data dir of one run shares; logProgress logs each dir as it starts.
|
||||
type runner struct {
|
||||
writer recordWriter
|
||||
extractors extractorsFunc
|
||||
retrieveKeys dirKeysFunc
|
||||
loginKeychain browser.LoginKeychain
|
||||
firefoxPassword func(context.Context) (string, error)
|
||||
logProgress bool
|
||||
maxStorageValue int
|
||||
writer recordWriter
|
||||
extractors extractorsFunc
|
||||
keySource keySource
|
||||
loginKeychain browser.LoginKeychain
|
||||
firefoxPrimaryPassword string
|
||||
logProgress bool
|
||||
maxStorageValue int
|
||||
}
|
||||
|
||||
// run ends at the first dir whose Summary has an Err, keeping what ran before it.
|
||||
@@ -105,16 +91,20 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories
|
||||
}
|
||||
dirSnapshot := root.Snapshot(string(dir.ID))
|
||||
|
||||
keys := &dirKeys{dir: dir, dirSnapshot: dirSnapshot}
|
||||
if dir.Browser.Base == browser.Chromium {
|
||||
keys.retrieve = r.retrieveKeys
|
||||
var masterKeys masterkey.Set
|
||||
if plan.needsMasterKeys {
|
||||
retrieval := r.keySource.MasterKeys(ctx, dir, dirSnapshot)
|
||||
masterKeys = retrieval.Keys
|
||||
if retrieval.Err != nil {
|
||||
summary.DirFailures = []DirFailure{{UserDataDirID: dir.ID, Err: fmt.Errorf("master key retrieval: %w", retrieval.Err)}}
|
||||
}
|
||||
}
|
||||
for _, extraction := range plan.extractions {
|
||||
if err := ctx.Err(); err != nil {
|
||||
summary.Err = fmt.Errorf("run stopped: %w", err)
|
||||
return summary
|
||||
}
|
||||
input := browser.NewInput(dirSnapshot, extraction.profile, keys.get, r.loginKeychain).WithFirefoxPassword(r.firefoxPassword)
|
||||
input := browser.NewInput(dirSnapshot, extraction.profile, masterKeys, r.loginKeychain).WithFirefoxPassword(r.firefoxPrimaryPassword)
|
||||
result, err := r.runExtraction(ctx, extraction, input, dir.Browser.DisplayName)
|
||||
if err != nil {
|
||||
summary.Err = err
|
||||
@@ -122,10 +112,6 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories
|
||||
}
|
||||
summary.Results = append(summary.Results, result)
|
||||
}
|
||||
if keys.err != nil {
|
||||
keyErr := fmt.Errorf("master key retrieval: %w", keys.err)
|
||||
summary.DirFailures = []DirFailure{{UserDataDirID: dir.ID, Err: keyErr}}
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
|
||||
@@ -37,11 +37,17 @@ func fakeBase(extractFuncs map[category.Category]extractFunc) extractorsFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func noKeys(t *testing.T) dirKeysFunc {
|
||||
return func(context.Context, browser.UserDataDir, snapshot.Snapshot) (masterkey.Set, error) {
|
||||
type keySourceFunc func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval
|
||||
|
||||
func (f keySourceFunc) MasterKeys(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval {
|
||||
return f(ctx, dir, dirSnapshot)
|
||||
}
|
||||
|
||||
func keysNeverRetrieved(t *testing.T) keySource {
|
||||
return keySourceFunc(func(context.Context, browser.UserDataDir, snapshot.Snapshot) masterkey.Retrieval {
|
||||
t.Error("keys were retrieved")
|
||||
return nil, nil
|
||||
}
|
||||
return masterkey.Retrieval{}
|
||||
})
|
||||
}
|
||||
|
||||
func chromeDir(t *testing.T, id browser.UserDataDirID, profiles ...string) browser.UserDataDir {
|
||||
@@ -54,10 +60,10 @@ func chromeDir(t *testing.T, id browser.UserDataDirID, profiles ...string) brows
|
||||
return dir
|
||||
}
|
||||
|
||||
func run(t *testing.T, base extractorsFunc, keys dirKeysFunc, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) {
|
||||
func run(t *testing.T, base extractorsFunc, keys keySource, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) {
|
||||
t.Helper()
|
||||
output := OutputOptions{Dir: t.TempDir()}
|
||||
summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, runner{extractors: base, retrieveKeys: keys})
|
||||
summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, runner{extractors: base, keySource: keys})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, summary.Err)
|
||||
return summary, output.Dir
|
||||
@@ -104,7 +110,7 @@ func TestExecute_Outcomes(t *testing.T) {
|
||||
category.Cookie, category.Password, category.History, category.Bookmark, category.Download, category.Extension,
|
||||
category.CreditCard,
|
||||
}
|
||||
summary, out := run(t, base, noKeys(t), categories, chromeDir(t, "chrome", "Default"))
|
||||
summary, out := run(t, base, noKeys{}, categories, chromeDir(t, "chrome", "Default"))
|
||||
|
||||
got := outcomes(summary)
|
||||
assert.Equal(t, OutcomePartial, got[category.Cookie].Outcome)
|
||||
@@ -137,7 +143,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, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: noKeys(t)})
|
||||
summary, err := execute(context.Background(), discovery, categories, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, keySource: noKeys{}})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, summary.Err)
|
||||
assert.Equal(t, []DirFailure{failed}, summary.DirFailures, "discovery's failures are reported with the run's")
|
||||
@@ -152,21 +158,21 @@ func TestExecute_ReportsEachDirWhatNeverRanFirst(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestExecute_KeysAreRetrievedOncePerUserDataDir(t *testing.T) {
|
||||
cookie := func(ctx context.Context, input browser.Input, out browser.Collector) error {
|
||||
out.Add(&record.Cookie{Value: string(input.MasterKeys(ctx)[masterkey.V10])})
|
||||
cookie := func(_ context.Context, input browser.Input, out browser.Collector) error {
|
||||
out.Add(&record.Cookie{Value: string(input.MasterKeys()[masterkey.V10])})
|
||||
return nil
|
||||
}
|
||||
login := func(ctx context.Context, input browser.Input, out browser.Collector) error {
|
||||
out.Add(&record.Login{Password: string(input.MasterKeys(ctx)[masterkey.V10])})
|
||||
login := func(_ context.Context, input browser.Input, out browser.Collector) error {
|
||||
out.Add(&record.Login{Password: string(input.MasterKeys()[masterkey.V10])})
|
||||
return nil
|
||||
}
|
||||
calls := 0
|
||||
keys := func(_ context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) {
|
||||
keys := keySourceFunc(func(_ context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval {
|
||||
calls++
|
||||
_, err := dirSnapshot.Path("Default/History")
|
||||
require.NoError(t, err, "keys are read from the dir's own snapshot")
|
||||
return masterkey.Set{masterkey.V10: []byte(dir.ID)}, errors.New("v20: no ABE")
|
||||
}
|
||||
return masterkey.Retrieval{Keys: masterkey.Set{masterkey.V10: []byte(dir.ID)}, Err: errors.New("v20: no ABE")}
|
||||
})
|
||||
base := fakeBase(map[category.Category]extractFunc{category.Cookie: cookie, category.Password: login})
|
||||
categories := []category.Category{category.Cookie, category.Password}
|
||||
|
||||
@@ -189,7 +195,7 @@ func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) {
|
||||
touch(t, path, "Default", "History")
|
||||
dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}}
|
||||
|
||||
run(t, extractorsFor, noKeys(t), []category.Category{category.History, category.Download}, dir)
|
||||
run(t, extractorsFor, keysNeverRetrieved(t), []category.Category{category.History, category.Download}, dir)
|
||||
}
|
||||
|
||||
func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) {
|
||||
@@ -206,7 +212,7 @@ func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) {
|
||||
return nil
|
||||
},
|
||||
})
|
||||
run(t, base, noKeys(t), []category.Category{category.History}, chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default"))
|
||||
run(t, base, keysNeverRetrieved(t), []category.Category{category.History}, chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default"))
|
||||
|
||||
require.Len(t, captured, 2)
|
||||
for _, path := range captured {
|
||||
@@ -235,7 +241,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")}}
|
||||
|
||||
summary, err := execute(ctx, discovery, categories, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, retrieveKeys: noKeys(t)})
|
||||
summary, err := execute(ctx, discovery, categories, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, keySource: keysNeverRetrieved(t)})
|
||||
require.NoError(t, err)
|
||||
require.ErrorIs(t, summary.Err, context.Canceled)
|
||||
require.Len(t, summary.Results, 1, "what ran before the stop is still reported")
|
||||
@@ -267,7 +273,7 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) {
|
||||
defer func() { require.NoError(t, os.Chmod(output.Dir, 0o700)) }()
|
||||
|
||||
discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}}
|
||||
summary, err := execute(context.Background(), discovery, []category.Category{category.History, category.Download}, output, runner{extractors: base, retrieveKeys: noKeys(t)})
|
||||
summary, err := execute(context.Background(), discovery, []category.Category{category.History, category.Download}, output, runner{extractors: base, keySource: keysNeverRetrieved(t)})
|
||||
require.NoError(t, err)
|
||||
require.Error(t, summary.Err)
|
||||
require.NotEmpty(t, copied)
|
||||
@@ -275,8 +281,7 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) {
|
||||
assert.ErrorIs(t, statErr, fs.ErrNotExist)
|
||||
}
|
||||
|
||||
// TestDump_FirefoxPasswordReadOnce: stdin yields the password once, yet every protected profile of the run needs it.
|
||||
func TestDump_FirefoxPasswordReadOnce(t *testing.T) {
|
||||
func TestDump_FirefoxPrimaryPasswordOpensEveryProtectedProfile(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
firefoxBrowser, ok := browser.Lookup("firefox")
|
||||
require.True(t, ok)
|
||||
@@ -285,15 +290,10 @@ func TestDump_FirefoxPasswordReadOnce(t *testing.T) {
|
||||
for _, profile := range []string{"a.default", "b.work"} {
|
||||
browsertest.WriteFirefoxPrimaryPasswordProfile(t, filepath.Join(profilesDir, profile), globalSalt, []byte("hunter2"), [][]byte{masterKey})
|
||||
}
|
||||
reads := 0
|
||||
password := func(context.Context) (string, error) {
|
||||
reads++
|
||||
return "hunter2", nil
|
||||
}
|
||||
|
||||
_, summary, err := Dump(context.Background(), DumpOptions{
|
||||
Browsers: []browser.Browser{firefoxBrowser}, HomeDir: home, Categories: []category.Category{category.Password},
|
||||
Output: OutputOptions{Dir: t.TempDir()}, FirefoxPassword: password,
|
||||
Output: OutputOptions{Dir: t.TempDir()}, FirefoxPrimaryPassword: "hunter2",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, summary.Err)
|
||||
@@ -301,5 +301,4 @@ func TestDump_FirefoxPasswordReadOnce(t *testing.T) {
|
||||
for _, result := range summary.Results {
|
||||
assert.Equal(t, OutcomeOK, result.Outcome, result.ProfileName)
|
||||
}
|
||||
assert.Equal(t, 1, reads, "one read serves every protected profile of the run")
|
||||
}
|
||||
@@ -59,11 +59,11 @@ func extractGoldenRun(t *testing.T, home string, keys map[browser.UserDataDirID]
|
||||
t.Helper()
|
||||
out := t.TempDir()
|
||||
flags := DumpFlags{Browser: "all", Categories: "all", Output: OutputFlags{Format: format, Dir: out, MaxStorageValue: DefaultMaxStorageValue}}
|
||||
options, err := ValidateDump(flags, nil, nil)
|
||||
options, err := ValidateDump(flags, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
discovery := discover(context.Background(), options.Browsers, browser.DiscoverOptions{HomeDir: home})
|
||||
fromFixture := runner{extractors: extractorsFor, retrieveKeys: keysFromFile(keys)}
|
||||
fromFixture := runner{extractors: extractorsFor, keySource: keyFileKeys(keys)}
|
||||
summary, err := execute(context.Background(), discovery, options.Categories, options.Output, fromFixture)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, summary.Err)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
)
|
||||
|
||||
// loginKeychain is the run's one login keychain, shared by Chromium's v10 key and Safari's passwords; nil off macOS.
|
||||
type loginKeychain interface {
|
||||
masterkey.LoginKeychain
|
||||
browser.LoginKeychain
|
||||
Err() error
|
||||
}
|
||||
|
||||
// warnIfLocked speaks once the run is over, because every reader of a locked keychain quietly gets metadata only.
|
||||
func warnIfLocked(ctx context.Context, loginKeychain loginKeychain, consequence string) {
|
||||
if loginKeychain == nil || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := loginKeychain.Err(); err != nil {
|
||||
log.Warnf("%v; %s", err, consequence)
|
||||
}
|
||||
}
|
||||
@@ -3,47 +3,16 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/keychain"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
)
|
||||
|
||||
// newLoginKeychain builds the run's login keychain without opening it, so a run that never decrypts never prompts.
|
||||
// A nil password, as list has it, leaves the keychain locked without a word.
|
||||
func newLoginKeychain(path string, password func(context.Context) (string, error)) loginKeychain {
|
||||
if password == nil {
|
||||
return keychain.New(path, func(context.Context) (string, error) { return "", nil })
|
||||
}
|
||||
return &reportingKeychain{Keychain: keychain.New(path, keychain.PasswordFunc(password))}
|
||||
func newLoginKeychain(path string, password keychain.PasswordFunc) loginKeychain {
|
||||
return keychain.New(path, 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.
|
||||
type reportingKeychain struct {
|
||||
*keychain.Keychain
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (k *reportingKeychain) GenericPassword(ctx context.Context, account string) ([]byte, error) {
|
||||
secret, err := k.Keychain.GenericPassword(ctx, account)
|
||||
k.warnLockedOnce()
|
||||
return secret, err
|
||||
}
|
||||
|
||||
func (k *reportingKeychain) InternetPasswords(ctx context.Context) ([]keychain.InternetPassword, error) {
|
||||
passwords, err := k.Keychain.InternetPasswords(ctx)
|
||||
k.warnLockedOnce()
|
||||
return passwords, err
|
||||
}
|
||||
|
||||
func (k *reportingKeychain) warnLockedOnce() {
|
||||
if err := k.Err(); err != nil {
|
||||
k.once.Do(func() { log.Warnf("%v; keychain-protected data is exported as metadata only", err) })
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
package app
|
||||
|
||||
import "context"
|
||||
import "github.com/moond4rk/hackbrowserdata/internal/keychain"
|
||||
|
||||
func newLoginKeychain(string, func(context.Context) (string, error)) loginKeychain { return nil }
|
||||
func newLoginKeychain(string, keychain.PasswordFunc) loginKeychain { return nil }
|
||||
|
||||
func loginKeychainPath(string) string { return "" }
|
||||
@@ -19,8 +19,8 @@ func List(ctx context.Context, detail bool) (Discovery, Summary, error) {
|
||||
if !detail || len(discovery.Dirs) == 0 {
|
||||
return discovery, Summary{}, nil
|
||||
}
|
||||
keychain := newLoginKeychain(loginKeychainPath(home), nil)
|
||||
counter := runner{writer: discard{}, extractors: extractorsFor, retrieveKeys: keysFromFile(nil), loginKeychain: keychain}
|
||||
loginKeychain := newLoginKeychain(loginKeychainPath(home), noPassword)
|
||||
counter := runner{writer: discard{}, extractors: extractorsFor, keySource: noKeys{}, loginKeychain: loginKeychain}
|
||||
summary := counter.run(ctx, discovery, category.All())
|
||||
if summary.Err != nil {
|
||||
return Discovery{}, Summary{}, summary.Err
|
||||
@@ -31,3 +31,6 @@ func List(ctx context.Context, detail bool) (Discovery, Summary, error) {
|
||||
type discard struct{}
|
||||
|
||||
func (discard) Write(category.Category, []record.Record) error { return nil }
|
||||
|
||||
// noPassword leaves the keychain locked, so counting never prompts.
|
||||
func noPassword(context.Context) (string, error) { return "", nil }
|
||||
+24
-37
@@ -2,7 +2,6 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
|
||||
@@ -10,47 +9,35 @@ import (
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
// loginKeychain is the run's one login keychain, shared by Chromium's v10 key and Safari's passwords; nil off macOS.
|
||||
type loginKeychain interface {
|
||||
masterkey.LoginKeychain
|
||||
browser.LoginKeychain
|
||||
// keySource is where a run gets each Chromium dir's master keys: this machine, a key file, or nowhere.
|
||||
type keySource interface {
|
||||
MasterKeys(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval
|
||||
}
|
||||
|
||||
type dirKeysFunc func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error)
|
||||
|
||||
// dirKeys retrieves a dir's keys on first use, for all its profiles; Go 1.20 has no sync.OnceValues.
|
||||
type dirKeys struct {
|
||||
once sync.Once
|
||||
retrieve dirKeysFunc // nil for a dir whose base keeps no master keys
|
||||
dir browser.UserDataDir
|
||||
dirSnapshot snapshot.Snapshot
|
||||
keys masterkey.Set
|
||||
err error
|
||||
// machineKeys asks this machine's secret stores; on macOS that includes the run's login keychain.
|
||||
type machineKeys struct {
|
||||
loginKeychain masterkey.LoginKeychain
|
||||
}
|
||||
|
||||
func (k *dirKeys) get(ctx context.Context) masterkey.Set {
|
||||
k.once.Do(func() {
|
||||
if k.retrieve != nil {
|
||||
k.keys, k.err = k.retrieve(ctx, k.dir, k.dirSnapshot)
|
||||
}
|
||||
})
|
||||
return k.keys
|
||||
}
|
||||
|
||||
// keysFromMachine asks this machine's secret stores; on macOS that includes the run's login keychain.
|
||||
func keysFromMachine(keychain masterkey.LoginKeychain) dirKeysFunc {
|
||||
return func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) {
|
||||
locator, err := chromium.KeyLocator(dir, dirSnapshot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locator.Keychain = keychain
|
||||
return masterkey.RetrieveAll(ctx, locator)
|
||||
func (k machineKeys) MasterKeys(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval {
|
||||
locator, err := chromium.KeyLocator(dir, dirSnapshot)
|
||||
if err != nil {
|
||||
return masterkey.Retrieval{Err: err}
|
||||
}
|
||||
locator.Keychain = k.loginKeychain
|
||||
return masterkey.RetrieveAll(ctx, locator)
|
||||
}
|
||||
|
||||
func keysFromFile(keys map[browser.UserDataDirID]masterkey.Set) dirKeysFunc {
|
||||
return func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) {
|
||||
return keys[dir.ID], nil
|
||||
}
|
||||
// keyFileKeys are a key file's master keys by dir; a dir it lacks gets none, so its encrypted values stay empty.
|
||||
type keyFileKeys map[browser.UserDataDirID]masterkey.Set
|
||||
|
||||
func (k keyFileKeys) MasterKeys(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) masterkey.Retrieval {
|
||||
return masterkey.Retrieval{Keys: k[dir.ID]}
|
||||
}
|
||||
|
||||
// noKeys lets list --detail count encrypted rows without retrieving a key, so counting never prompts.
|
||||
type noKeys struct{}
|
||||
|
||||
func (noKeys) MasterKeys(context.Context, browser.UserDataDir, snapshot.Snapshot) masterkey.Retrieval {
|
||||
return masterkey.Retrieval{}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
func TestKeysFromFile(t *testing.T) {
|
||||
want := masterkey.Set{masterkey.V10: []byte("dumped")}
|
||||
keys := keysFromFile(map[browser.UserDataDirID]masterkey.Set{"chrome": want})
|
||||
got, err := keys(context.Background(), browser.UserDataDir{ID: "chrome"}, snapshot.Snapshot{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got)
|
||||
|
||||
got, err = keys(context.Background(), browser.UserDataDir{ID: "edge"}, snapshot.Snapshot{})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, got, "a key file without the dir's keys decrypts nothing")
|
||||
}
|
||||
@@ -13,9 +13,10 @@ import (
|
||||
|
||||
// dirPlan is what runDir does for one user data dir, decided from which files exist before anything is copied.
|
||||
type dirPlan struct {
|
||||
extractions []plannedExtraction // to run, in output order
|
||||
files []snapshot.File // what they read, each copied once
|
||||
skipped []Result // requested extractions that will not run, and why
|
||||
extractions []plannedExtraction // to run, in output order
|
||||
files []snapshot.File // what they read, each copied once
|
||||
skipped []Result // requested extractions that will not run, and why
|
||||
needsMasterKeys bool // an extraction decrypts with the dir's master keys, so they are retrieved once
|
||||
}
|
||||
|
||||
// plannedExtraction keeps the extractor that planning checked, so the run uses that same extractor.
|
||||
@@ -48,6 +49,7 @@ func planDir(dir browser.UserDataDir, categories []category.Category, extractors
|
||||
default:
|
||||
plan.extractions = append(plan.extractions, plannedExtraction{Extraction: extraction, profile: profile, extractor: extractor})
|
||||
plan.files = appendNew(plan.files, captured, files...)
|
||||
plan.needsMasterKeys = plan.needsMasterKeys || needsMasterKeys(dir, dataCategory)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func Restore(ctx context.Context, options RestoreOptions) (Discovery, Summary, e
|
||||
if len(discovery.Dirs) == 0 {
|
||||
return discovery, Summary{}, nil
|
||||
}
|
||||
fromKeyFile := runner{extractors: extractorsFor, retrieveKeys: keysFromFile(keys)}
|
||||
fromKeyFile := runner{extractors: extractorsFor, keySource: keyFileKeys(keys)}
|
||||
summary, err := execute(ctx, discovery, options.Categories, options.Output, fromKeyFile)
|
||||
if err != nil {
|
||||
return Discovery{}, Summary{}, err
|
||||
|
||||
@@ -90,13 +90,3 @@ func decryptCBC(key, ciphertext []byte) ([]byte, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// masterKeysFunc returns the dir's master keys, which the first call may retrieve; an empty value never calls it.
|
||||
type masterKeysFunc func() masterkey.Set
|
||||
|
||||
func (keys masterKeysFunc) decrypt(ciphertext []byte) ([]byte, error) {
|
||||
if len(ciphertext) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return decryptValue(keys(), ciphertext)
|
||||
}
|
||||
@@ -235,14 +235,8 @@ func TestDecrypt_ShortCiphertext(t *testing.T) {
|
||||
require.ErrorIs(t, err, errShortCiphertext)
|
||||
}
|
||||
|
||||
func TestMasterKeysFuncDecrypt_EmptyValueFetchesNoKey(t *testing.T) {
|
||||
fetched := false
|
||||
keys := masterKeysFunc(func() masterkey.Set {
|
||||
fetched = true
|
||||
return nil
|
||||
})
|
||||
plaintext, err := keys.decrypt(nil)
|
||||
require.NoError(t, err)
|
||||
func TestDecryptValue_EmptyValueNeedsNoKey(t *testing.T) {
|
||||
plaintext, err := decryptValue(nil, nil)
|
||||
require.NoError(t, err, "an empty column is not a failed decryption")
|
||||
assert.Nil(t, plaintext)
|
||||
assert.False(t, fetched, "an empty value must not trigger key retrieval")
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/sqlitex"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/timeconv"
|
||||
@@ -15,7 +16,7 @@ const cookieQuery = `SELECT name, encrypted_value, host_key, path,
|
||||
creation_utc, expires_utc, is_secure, is_httponly,
|
||||
has_expires, is_persistent, samesite FROM cookies`
|
||||
|
||||
func extractCookies(masterKeys masterKeysFunc, path string, out browser.Collector) error {
|
||||
func extractCookies(masterKeys masterkey.Set, path string, out browser.Collector) error {
|
||||
database, err := sqlitex.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -44,7 +45,7 @@ func extractCookies(masterKeys masterKeysFunc, path string, out browser.Collecto
|
||||
continue
|
||||
}
|
||||
|
||||
value, err := masterKeys.decrypt(encryptedValue)
|
||||
value, err := decryptValue(masterKeys, encryptedValue)
|
||||
if err != nil {
|
||||
out.Fail(fmt.Errorf("decrypt cookie %s on %s: %w", name, host, err))
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestExtractCookies(t *testing.T) {
|
||||
path := setupCookieDB(t)
|
||||
|
||||
var out testCollector
|
||||
err := extractCookies(keysOf(masterkey.Set{}), path, &out)
|
||||
err := extractCookies(masterkey.Set{}, path, &out)
|
||||
got := collected[record.Cookie](t, &out)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
@@ -51,7 +51,7 @@ func TestExtractCookies_UndecryptableValueStillListed(t *testing.T) {
|
||||
insertCookie("SID", ".enc.com", "/", "763130deadbeef", 13350000000000000, 13360000000000000, 1, 1))
|
||||
|
||||
var out testCollector
|
||||
require.NoError(t, extractCookies(keysOf(masterkey.Set{}), path, &out))
|
||||
require.NoError(t, extractCookies(masterkey.Set{}, path, &out))
|
||||
got := collected[record.Cookie](t, &out)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "SID", got[0].Name)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/sqlitex"
|
||||
)
|
||||
@@ -13,7 +14,7 @@ const (
|
||||
card_number_encrypted, COALESCE(nickname, ''), COALESCE(billing_address_id, '') FROM credit_cards`
|
||||
)
|
||||
|
||||
func extractCreditCards(masterKeys masterKeysFunc, path string, out browser.Collector) error {
|
||||
func extractCreditCards(masterKeys masterkey.Set, path string, out browser.Collector) error {
|
||||
database, err := sqlitex.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -33,7 +34,7 @@ func extractCreditCards(masterKeys masterKeysFunc, path string, out browser.Coll
|
||||
out.Fail(err)
|
||||
continue
|
||||
}
|
||||
number, err := masterKeys.decrypt(encryptedNumber)
|
||||
number, err := decryptValue(masterKeys, encryptedNumber)
|
||||
if err != nil {
|
||||
out.Fail(fmt.Errorf("decrypt card %s: %w", guid, err))
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestExtractCreditCards(t *testing.T) {
|
||||
path := setupCreditCardDB(t)
|
||||
|
||||
var out testCollector
|
||||
err := extractCreditCards(keysOf(masterkey.Set{}), path, &out)
|
||||
err := extractCreditCards(masterkey.Set{}, path, &out)
|
||||
got := collected[record.CreditCard](t, &out)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/sqlitex"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/timeconv"
|
||||
@@ -17,7 +18,7 @@ const (
|
||||
// accountLoginData holds the signed-in account's logins, which Chrome keeps apart from Login Data.
|
||||
const accountLoginData = "Login Data For Account"
|
||||
|
||||
func extractPasswords(masterKeys masterKeysFunc, path string, out browser.Collector) error {
|
||||
func extractPasswords(masterKeys masterkey.Set, path string, out browser.Collector) error {
|
||||
store := record.StoreLocal
|
||||
if filepath.Base(path) == accountLoginData {
|
||||
store = record.StoreAccount
|
||||
@@ -42,7 +43,7 @@ func extractPasswords(masterKeys masterKeysFunc, path string, out browser.Collec
|
||||
out.Fail(err)
|
||||
continue
|
||||
}
|
||||
password, err := masterKeys.decrypt(encryptedPassword)
|
||||
password, err := decryptValue(masterKeys, encryptedPassword)
|
||||
if err != nil {
|
||||
out.Fail(fmt.Errorf("decrypt password for %s: %w", url, err))
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestExtractPasswords(t *testing.T) {
|
||||
path := setupLoginDB(t)
|
||||
|
||||
var out testCollector
|
||||
err := extractPasswords(keysOf(masterkey.Set{}), path, &out)
|
||||
err := extractPasswords(masterkey.Set{}, path, &out)
|
||||
got := collected[record.Login](t, &out)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
@@ -45,7 +45,7 @@ func TestExtractPasswords_UndecryptableBlobStillListed(t *testing.T) {
|
||||
)
|
||||
|
||||
var out testCollector
|
||||
err := extractPasswords(keysOf(masterkey.Set{}), path, &out)
|
||||
err := extractPasswords(masterkey.Set{}, path, &out)
|
||||
got := collected[record.Login](t, &out)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
|
||||
@@ -38,6 +38,17 @@ var defaultExtractors = browser.Extractors{
|
||||
category.SessionStorage: newPlainExtractor(extractSessionStorage, sessionStorage),
|
||||
}
|
||||
|
||||
// NeedsMasterKeys reports whether dataCategory's values are sealed with the dir's master keys, so a run that asks only
|
||||
// for the others never retrieves a key.
|
||||
func NeedsMasterKeys(dataCategory category.Category) bool {
|
||||
switch dataCategory {
|
||||
case category.Password, category.Cookie, category.CreditCard:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// withoutExtensionList names forks whose Preferences files hold no extension list, so extensions are unsupported there.
|
||||
var withoutExtensionList = map[string]bool{"qq": true, "sogou": true}
|
||||
|
||||
@@ -63,11 +74,11 @@ func kindExtractors(vaultKind string) browser.Extractors {
|
||||
}
|
||||
|
||||
// newDecryptingExtractor parses each file in turn, so a store that is missing or broken keeps the others' records.
|
||||
func newDecryptingExtractor(parse func(masterKeysFunc, string, browser.Collector) error, sources ...browser.Source) browser.Extractor {
|
||||
func newDecryptingExtractor(parse func(masterkey.Set, string, browser.Collector) error, sources ...browser.Source) browser.Extractor {
|
||||
return browser.Extractor{
|
||||
// The dir's master keys come from KeySources, so a decrypting extraction must find them in the snapshot too.
|
||||
Sources: append(sources, KeySources()...),
|
||||
Extract: func(ctx context.Context, input browser.Input, out browser.Collector) error {
|
||||
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
|
||||
var errs []error
|
||||
for _, source := range sources {
|
||||
path, err := input.Path(source)
|
||||
@@ -75,7 +86,7 @@ func newDecryptingExtractor(parse func(masterKeysFunc, string, browser.Collector
|
||||
continue
|
||||
}
|
||||
if err == nil {
|
||||
err = parse(masterKeysOf(ctx, input), path, out)
|
||||
err = parse(input.MasterKeys(), path, out)
|
||||
}
|
||||
errs = append(errs, err)
|
||||
}
|
||||
@@ -84,10 +95,6 @@ func newDecryptingExtractor(parse func(masterKeysFunc, string, browser.Collector
|
||||
}
|
||||
}
|
||||
|
||||
func masterKeysOf(ctx context.Context, input browser.Input) masterKeysFunc {
|
||||
return func() masterkey.Set { return input.MasterKeys(ctx) }
|
||||
}
|
||||
|
||||
func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor {
|
||||
return browser.Extractor{
|
||||
Sources: []browser.Source{source},
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/browsertest"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
@@ -259,8 +258,3 @@ func collected[T any](t *testing.T, collector *testCollector) []T {
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// keysOf hands an extractor fixed master keys, as a dir whose keys were already retrieved would.
|
||||
func keysOf(masterKeys masterkey.Set) masterKeysFunc {
|
||||
return func() masterkey.Set { return masterKeys }
|
||||
}
|
||||
@@ -131,7 +131,7 @@ const yandexLoginQuery = `SELECT origin_url, username_element, username_value,
|
||||
password_element, password_value, signon_realm, date_created FROM logins`
|
||||
|
||||
// extractYandexPasswords reads origin_url, which the per-row AAD covers, not action_url.
|
||||
func extractYandexPasswords(masterKeys masterKeysFunc, path string, out browser.Collector) error {
|
||||
func extractYandexPasswords(masterKeys masterkey.Set, path string, out browser.Collector) error {
|
||||
database, err := sqlitex.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -164,7 +164,7 @@ func extractYandexPasswords(masterKeys masterKeysFunc, path string, out browser.
|
||||
Store: record.StoreLocal,
|
||||
}
|
||||
if dataKey == nil && keyErr == nil {
|
||||
dataKey, keyErr = loadYandexDataKey(path, masterKeys()[masterkey.V10])
|
||||
dataKey, keyErr = loadYandexDataKey(path, masterKeys[masterkey.V10])
|
||||
}
|
||||
if dataKey == nil {
|
||||
out.Fail(fmt.Errorf("yandex: password for %s: %w", originURL, keyErr))
|
||||
@@ -200,7 +200,7 @@ type yandexPrivateData struct {
|
||||
}
|
||||
|
||||
// extractYandexCreditCards reads the records table (not Chromium's credit_cards). AAD = guid.
|
||||
func extractYandexCreditCards(masterKeys masterKeysFunc, path string, out browser.Collector) error {
|
||||
func extractYandexCreditCards(masterKeys masterkey.Set, path string, out browser.Collector) error {
|
||||
database, err := sqlitex.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -240,7 +240,7 @@ func extractYandexCreditCards(masterKeys masterKeysFunc, path string, out browse
|
||||
NickName: public.CardTitle,
|
||||
}
|
||||
if dataKey == nil && keyErr == nil {
|
||||
dataKey, keyErr = loadYandexDataKey(path, masterKeys()[masterkey.V10])
|
||||
dataKey, keyErr = loadYandexDataKey(path, masterKeys[masterkey.V10])
|
||||
}
|
||||
if dataKey == nil {
|
||||
out.Fail(fmt.Errorf("yandex: card %s: %w", guid, keyErr))
|
||||
|
||||
@@ -102,7 +102,7 @@ func TestExtractYandexPasswords(t *testing.T) {
|
||||
)
|
||||
|
||||
var out testCollector
|
||||
err := extractYandexPasswords(keysOf(masterkey.Set{masterkey.V10: masterKey}), path, &out)
|
||||
err := extractYandexPasswords(masterkey.Set{masterkey.V10: masterKey}, path, &out)
|
||||
got := collected[record.Login](t, &out)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
@@ -128,7 +128,7 @@ func TestExtractYandexPasswords_MasterPasswordKeepsTheLogins(t *testing.T) {
|
||||
)
|
||||
|
||||
var out testCollector
|
||||
require.NoError(t, extractYandexPasswords(keysOf(masterkey.Set{masterkey.V10: masterKey}), path, &out))
|
||||
require.NoError(t, extractYandexPasswords(masterkey.Set{masterkey.V10: masterKey}, path, &out))
|
||||
logins := collected[record.Login](t, &out)
|
||||
require.Len(t, logins, 1)
|
||||
assert.Equal(t, "alice", logins[0].Username)
|
||||
@@ -146,7 +146,7 @@ func TestExtractYandexPasswords_WithoutAKeyKeepsTheLogins(t *testing.T) {
|
||||
)
|
||||
|
||||
var out testCollector
|
||||
require.NoError(t, extractYandexPasswords(keysOf(nil), path, &out))
|
||||
require.NoError(t, extractYandexPasswords(nil, path, &out))
|
||||
logins := collected[record.Login](t, &out)
|
||||
require.Len(t, logins, 2)
|
||||
for _, login := range logins {
|
||||
@@ -169,7 +169,7 @@ func TestExtractYandexPasswords_WrongMasterKey(t *testing.T) {
|
||||
|
||||
// A wrong master key fails at the intermediate step, so the login exports without its password.
|
||||
var out testCollector
|
||||
require.NoError(t, extractYandexPasswords(keysOf(masterkey.Set{masterkey.V10: wrongKey}), path, &out))
|
||||
require.NoError(t, extractYandexPasswords(masterkey.Set{masterkey.V10: wrongKey}, path, &out))
|
||||
logins := collected[record.Login](t, &out)
|
||||
require.Len(t, logins, 1)
|
||||
assert.Empty(t, logins[0].Password)
|
||||
@@ -222,7 +222,7 @@ func TestExtractYandexCreditCards(t *testing.T) {
|
||||
)
|
||||
|
||||
var out testCollector
|
||||
err := extractYandexCreditCards(keysOf(masterkey.Set{masterkey.V10: masterKey}), path, &out)
|
||||
err := extractYandexCreditCards(masterkey.Set{masterkey.V10: masterKey}, path, &out)
|
||||
got := collected[record.CreditCard](t, &out)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
@@ -258,7 +258,7 @@ func TestExtractYandexCreditCards_WrongMasterKey(t *testing.T) {
|
||||
)
|
||||
|
||||
var out testCollector
|
||||
require.NoError(t, extractYandexCreditCards(keysOf(masterkey.Set{masterkey.V10: wrongKey}), path, &out))
|
||||
require.NoError(t, extractYandexCreditCards(masterkey.Set{masterkey.V10: wrongKey}, path, &out))
|
||||
cards := collected[record.CreditCard](t, &out)
|
||||
require.Len(t, cards, 1, "the card exports without its number")
|
||||
assert.Equal(t, "g1", cards[0].GUID)
|
||||
@@ -274,14 +274,9 @@ func TestYandexCardAAD(t *testing.T) {
|
||||
assert.Equal(t, "gID", string(got))
|
||||
}
|
||||
|
||||
func TestExtractYandexPasswords_EmptyTableFetchesNoKey(t *testing.T) {
|
||||
func TestExtractYandexPasswords_EmptyTableNeedsNoKey(t *testing.T) {
|
||||
path := setupYandexPasswordDB(t, bytes.Repeat([]byte{0x11}, 32), bytes.Repeat([]byte{0x22}, 32), false)
|
||||
fetched := false
|
||||
keys := masterKeysFunc(func() masterkey.Set {
|
||||
fetched = true
|
||||
return nil
|
||||
})
|
||||
var out testCollector
|
||||
require.NoError(t, extractYandexPasswords(keys, path, &out))
|
||||
assert.False(t, fetched, "a table without rows must not trigger key retrieval")
|
||||
require.NoError(t, extractYandexPasswords(nil, path, &out))
|
||||
assert.Empty(t, out.fails, "a table without rows loads no data key, so a missing master key fails nothing")
|
||||
}
|
||||
@@ -62,16 +62,14 @@ type LoginKeychain interface {
|
||||
type Input struct {
|
||||
Profile Profile
|
||||
snapshot snapshot.Snapshot
|
||||
masterKeys func(ctx context.Context) masterkey.Set
|
||||
masterKeys masterkey.Set
|
||||
loginKeychain LoginKeychain
|
||||
firefoxPassword func(ctx context.Context) (string, error)
|
||||
firefoxPassword string
|
||||
}
|
||||
|
||||
// NewInput takes masterKeys, the dir's call-once retrieval, nil for bases that keep no Chromium keys, and the run's
|
||||
// login keychain, nil off macOS and in a restore.
|
||||
func NewInput(
|
||||
dirSnapshot snapshot.Snapshot, profile Profile, masterKeys func(context.Context) masterkey.Set, loginKeychain LoginKeychain,
|
||||
) Input {
|
||||
// NewInput takes the dir's master keys, nil for bases that keep none, and the run's login keychain, nil off macOS and
|
||||
// in a restore.
|
||||
func NewInput(dirSnapshot snapshot.Snapshot, profile Profile, masterKeys masterkey.Set, loginKeychain LoginKeychain) Input {
|
||||
return Input{Profile: profile, snapshot: dirSnapshot, masterKeys: masterKeys, loginKeychain: loginKeychain}
|
||||
}
|
||||
|
||||
@@ -87,28 +85,22 @@ func (in Input) Path(source Source) (string, error) {
|
||||
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.
|
||||
func (in Input) MasterKeys(ctx context.Context) masterkey.Set {
|
||||
if in.masterKeys == nil {
|
||||
return nil
|
||||
}
|
||||
return in.masterKeys(ctx)
|
||||
// MasterKeys lacks each key version that could not be retrieved.
|
||||
func (in Input) MasterKeys() masterkey.Set {
|
||||
return in.masterKeys
|
||||
}
|
||||
|
||||
func (in Input) LoginKeychain() LoginKeychain {
|
||||
return in.loginKeychain
|
||||
}
|
||||
|
||||
// WithFirefoxPassword sets the lazy Firefox primary-password source; only the dump path supplies one.
|
||||
func (in Input) WithFirefoxPassword(password func(context.Context) (string, error)) Input {
|
||||
// WithFirefoxPassword sets the Firefox primary password; only the dump path supplies one.
|
||||
func (in Input) WithFirefoxPassword(password string) Input {
|
||||
in.firefoxPassword = password
|
||||
return in
|
||||
}
|
||||
|
||||
// FirefoxPrimaryPassword is the user's primary password, "" when none was given; it may block on first use.
|
||||
func (in Input) FirefoxPrimaryPassword(ctx context.Context) (string, error) {
|
||||
if in.firefoxPassword == nil {
|
||||
return "", nil
|
||||
}
|
||||
return in.firefoxPassword(ctx)
|
||||
// FirefoxPrimaryPassword is the user's primary password, "" when none was given.
|
||||
func (in Input) FirefoxPrimaryPassword() string {
|
||||
return in.firefoxPassword
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
@@ -71,20 +70,6 @@ func TestInputPath_FailedCopyIsReported(t *testing.T) {
|
||||
assert.NotErrorIs(t, err, fs.ErrNotExist)
|
||||
}
|
||||
|
||||
func TestInputMasterKeys(t *testing.T) {
|
||||
dirSnapshot := snapshot.Open(t.TempDir()).Snapshot("chrome")
|
||||
assert.Nil(t, NewInput(dirSnapshot, Profile{}, nil, nil).MasterKeys(context.Background()))
|
||||
|
||||
calls := 0
|
||||
want := masterkey.Set{masterkey.V10: []byte("k")}
|
||||
input := NewInput(dirSnapshot, Profile{}, func(context.Context) masterkey.Set {
|
||||
calls++
|
||||
return want
|
||||
}, nil)
|
||||
assert.Equal(t, want, input.MasterKeys(context.Background()))
|
||||
assert.Equal(t, 1, calls)
|
||||
}
|
||||
|
||||
func TestSourceCandidatePaths(t *testing.T) {
|
||||
profile := Profile{Name: "Default", RelativePath: "Default"}
|
||||
assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}.CandidatePaths(profile))
|
||||
|
||||
@@ -134,25 +134,21 @@ func newPlainExtractor(parse func(string, browser.Collector) error, source brows
|
||||
func newDecryptingExtractor(parse func(func() ([]byte, error), string, browser.Collector) error, source browser.Source) browser.Extractor {
|
||||
return browser.Extractor{
|
||||
Sources: []browser.Source{source, keyStore},
|
||||
Extract: func(ctx context.Context, input browser.Input, out browser.Collector) error {
|
||||
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
|
||||
path, err := input.Path(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
masterKey := func() ([]byte, error) { return profileKey(ctx, input, path) }
|
||||
masterKey := func() ([]byte, error) { return profileKey(input, path) }
|
||||
return parse(masterKey, path, out)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func profileKey(ctx context.Context, input browser.Input, loginsPath string) ([]byte, error) {
|
||||
func profileKey(input browser.Input, loginsPath string) ([]byte, error) {
|
||||
key4Path, err := input.Path(keyStore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
primaryPassword := func() ([]byte, error) {
|
||||
password, err := input.FirefoxPrimaryPassword(ctx)
|
||||
return []byte(password), err
|
||||
}
|
||||
return retrieveMasterKey(key4Path, loginsPath, primaryPassword)
|
||||
return retrieveMasterKey(key4Path, loginsPath, []byte(input.FirefoxPrimaryPassword()))
|
||||
}
|
||||
@@ -15,9 +15,7 @@ import (
|
||||
)
|
||||
|
||||
// retrieveMasterKey derives the key candidates in key4.db and returns the one that opens the logins in loginsPath.
|
||||
// primaryPassword is read only when a profile turns out to have one, so a run of mostly-unprotected profiles never
|
||||
// blocks on stdin or a prompt it does not need.
|
||||
func retrieveMasterKey(key4Path, loginsPath string, primaryPassword func() ([]byte, error)) ([]byte, error) {
|
||||
func retrieveMasterKey(key4Path, loginsPath string, primaryPassword []byte) ([]byte, error) {
|
||||
key4, err := readKey4DB(key4Path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -96,7 +94,7 @@ var (
|
||||
errPrimaryPasswordWrong = errors.New("primary password is incorrect")
|
||||
)
|
||||
|
||||
func (k *key4DB) deriveKeys(primaryPassword func() ([]byte, error)) ([][]byte, error) {
|
||||
func (k *key4DB) deriveKeys(primaryPassword []byte) ([][]byte, error) {
|
||||
password, err := k.selectPassword(primaryPassword)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -117,10 +115,9 @@ func (k *key4DB) deriveKeys(primaryPassword func() ([]byte, error)) ([][]byte, e
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// selectPassword uses the empty password for a profile with no primary password, else the user's once it checks out,
|
||||
// reading primaryPassword (which may block) only when the empty one does not fit. A passwordCheck that will not parse
|
||||
// is a corrupt DB, reported as such rather than as a wrong password.
|
||||
func (k *key4DB) selectPassword(primaryPassword func() ([]byte, error)) ([]byte, error) {
|
||||
// selectPassword uses the empty password for a profile with no primary password, else the user's once it checks out.
|
||||
// A passwordCheck that will not parse is a corrupt DB, reported as such rather than as a wrong password.
|
||||
func (k *key4DB) selectPassword(primaryPassword []byte) ([]byte, error) {
|
||||
pbe, err := crypto.NewASN1PBE(k.passwordCheck)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse key4.db password check: %w", err)
|
||||
@@ -128,14 +125,10 @@ func (k *key4DB) selectPassword(primaryPassword func() ([]byte, error)) ([]byte,
|
||||
if passwordChecks(pbe, crypto.NSSPasswordKey(k.globalSalt, nil)) {
|
||||
return nil, nil
|
||||
}
|
||||
password, err := primaryPassword()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(primaryPassword) > 0 && passwordChecks(pbe, crypto.NSSPasswordKey(k.globalSalt, primaryPassword)) {
|
||||
return primaryPassword, nil
|
||||
}
|
||||
if len(password) > 0 && passwordChecks(pbe, crypto.NSSPasswordKey(k.globalSalt, password)) {
|
||||
return password, nil
|
||||
}
|
||||
if len(password) == 0 {
|
||||
if len(primaryPassword) == 0 {
|
||||
return nil, errPrimaryPasswordRequired
|
||||
}
|
||||
return nil, errPrimaryPasswordWrong
|
||||
|
||||
@@ -30,28 +30,19 @@ func passwordCheckFor(t *testing.T, globalSalt, password []byte) []byte {
|
||||
return append(append([]byte(nil), blob[:len(blob)-len(cipher)]...), cipher...)
|
||||
}
|
||||
|
||||
func constPassword(password string) func() ([]byte, error) {
|
||||
return func() ([]byte, error) {
|
||||
if password == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return []byte(password), nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectPassword_PrimaryPassword(t *testing.T) {
|
||||
globalSalt := bytes.Repeat([]byte("moond4rk"), 3)
|
||||
const password = "hunter2"
|
||||
key4 := &key4DB{globalSalt: globalSalt, passwordCheck: passwordCheckFor(t, globalSalt, []byte(password))}
|
||||
|
||||
selected, err := key4.selectPassword(constPassword(password))
|
||||
selected, err := key4.selectPassword([]byte(password))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte(password), selected, "the right primary password is selected")
|
||||
|
||||
_, err = key4.selectPassword(constPassword(""))
|
||||
_, err = key4.selectPassword(nil)
|
||||
require.ErrorIs(t, err, errPrimaryPasswordRequired, "a protected profile with no password asks for one")
|
||||
|
||||
_, err = key4.selectPassword(constPassword("wrong"))
|
||||
_, err = key4.selectPassword([]byte("wrong"))
|
||||
require.ErrorIs(t, err, errPrimaryPasswordWrong, "a wrong password is reported as wrong")
|
||||
}
|
||||
|
||||
@@ -59,18 +50,15 @@ func TestSelectPassword_NoPrimaryPassword(t *testing.T) {
|
||||
globalSalt := bytes.Repeat([]byte("moond4rk"), 3)
|
||||
key4 := &key4DB{globalSalt: globalSalt, passwordCheck: passwordCheckFor(t, globalSalt, nil)}
|
||||
|
||||
selected, err := key4.selectPassword(func() ([]byte, error) {
|
||||
t.Fatal("must not read the user's password when the empty one fits")
|
||||
return nil, nil
|
||||
})
|
||||
selected, err := key4.selectPassword([]byte("hunter2"))
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, selected, "the empty password is used")
|
||||
assert.Nil(t, selected, "the empty password fits, so a given one is not used")
|
||||
}
|
||||
|
||||
func TestSelectPassword_CorruptCheck(t *testing.T) {
|
||||
// A password check that will not parse is a corrupt DB, not a wrong or missing password.
|
||||
key4 := &key4DB{globalSalt: []byte("salt"), passwordCheck: []byte("not a valid pbe blob")}
|
||||
_, err := key4.selectPassword(constPassword("whatever"))
|
||||
_, err := key4.selectPassword([]byte("whatever"))
|
||||
require.Error(t, err)
|
||||
require.NotErrorIs(t, err, errPrimaryPasswordRequired)
|
||||
require.NotErrorIs(t, err, errPrimaryPasswordWrong)
|
||||
@@ -84,13 +72,13 @@ func TestRetrieveMasterKey_PrimaryPassword(t *testing.T) {
|
||||
browsertest.WriteFirefoxPrimaryPasswordProfile(t, dir, globalSalt, password, [][]byte{masterKey})
|
||||
key4, logins := filepath.Join(dir, "key4.db"), filepath.Join(dir, "logins.json")
|
||||
|
||||
got, err := retrieveMasterKey(key4, logins, constPassword(string(password)))
|
||||
got, err := retrieveMasterKey(key4, logins, password)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, masterKey, got, "the right password recovers the master key")
|
||||
|
||||
_, err = retrieveMasterKey(key4, logins, constPassword(""))
|
||||
_, err = retrieveMasterKey(key4, logins, nil)
|
||||
require.ErrorIs(t, err, errPrimaryPasswordRequired, "a protected profile with no password asks for one")
|
||||
|
||||
_, err = retrieveMasterKey(key4, logins, constPassword("wrong"))
|
||||
_, err = retrieveMasterKey(key4, logins, []byte("wrong"))
|
||||
require.ErrorIs(t, err, errPrimaryPasswordWrong, "a wrong password is reported as wrong")
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
// Package keychain owns the user's macOS login keychain: one handle per run, opened on first use.
|
||||
package keychain
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PasswordFunc yields the login password; "" means none was supplied.
|
||||
type PasswordFunc func(ctx context.Context) (string, error)
|
||||
|
||||
// InternetPassword is one internet password item; Password is empty while the keychain stays locked.
|
||||
type InternetPassword struct {
|
||||
|
||||
@@ -9,9 +9,6 @@ import (
|
||||
"github.com/moond4rk/keychainbreaker"
|
||||
)
|
||||
|
||||
// PasswordFunc yields the login password; "" means none was supplied.
|
||||
type PasswordFunc func(ctx context.Context) (string, error)
|
||||
|
||||
// ErrLocked reports that no usable password was supplied, so the keychain yields metadata only.
|
||||
var ErrLocked = errors.New("login keychain is locked")
|
||||
|
||||
|
||||
@@ -59,12 +59,18 @@ const (
|
||||
ABEAvast
|
||||
)
|
||||
|
||||
// RetrieveAll keeps the first key per version and reports an error only when every retriever of that version fails.
|
||||
func RetrieveAll(ctx context.Context, locator Locator) (Set, error) {
|
||||
// Retrieval keeps the keys that worked beside Err, since one version failing never discards another.
|
||||
type Retrieval struct {
|
||||
Keys Set
|
||||
Err error // the versions whose every retriever failed; nil when none did
|
||||
}
|
||||
|
||||
// RetrieveAll keeps the first key per version; a version fails only when every one of its retrievers fails.
|
||||
func RetrieveAll(ctx context.Context, locator Locator) Retrieval {
|
||||
return retrieveAll(ctx, locator, platformRetrievers)
|
||||
}
|
||||
|
||||
func retrieveAll(ctx context.Context, locator Locator, retrievers []keyRetriever) (Set, error) {
|
||||
func retrieveAll(ctx context.Context, locator Locator, retrievers []keyRetriever) Retrieval {
|
||||
keys := make(Set)
|
||||
var versions []Version
|
||||
failures := make(map[Version][]error)
|
||||
@@ -94,5 +100,5 @@ func retrieveAll(ctx context.Context, locator Locator, retrievers []keyRetriever
|
||||
errs = append(errs, fmt.Errorf("%s: %w", version, errors.Join(failures[version]...)))
|
||||
}
|
||||
}
|
||||
return keys, errors.Join(errs...)
|
||||
return Retrieval{Keys: keys, Err: errors.Join(errs...)}
|
||||
}
|
||||
@@ -63,9 +63,9 @@ func TestRetrieveAll_OneKeyPerVersion(t *testing.T) {
|
||||
}
|
||||
for _, testCase := range tests {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
got, err := retrieveAll(context.Background(), Locator{}, asRetrievers(testCase.retrievers))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.want, got)
|
||||
retrieval := retrieveAll(context.Background(), Locator{}, asRetrievers(testCase.retrievers))
|
||||
require.NoError(t, retrieval.Err)
|
||||
assert.Equal(t, testCase.want, retrieval.Keys)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -75,50 +75,50 @@ func TestRetrieveAll_FirstKeyWinsAndStopsTheVersion(t *testing.T) {
|
||||
winner := &fakeRetriever{version: V10, key: v10Key}
|
||||
later := &fakeRetriever{version: V10, key: bytes.Repeat([]byte{0xFF}, 16)}
|
||||
|
||||
got, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{failing, winner, later})
|
||||
require.NoError(t, err, "a strategy that failed before a later one succeeded is not an error")
|
||||
assert.Equal(t, Set{V10: v10Key}, got)
|
||||
retrieval := retrieveAll(context.Background(), Locator{}, []keyRetriever{failing, winner, later})
|
||||
require.NoError(t, retrieval.Err, "a strategy that failed before a later one succeeded is not an error")
|
||||
assert.Equal(t, Set{V10: v10Key}, retrieval.Keys)
|
||||
assert.Equal(t, []int{1, 1, 0}, []int{failing.calls, winner.calls, later.calls})
|
||||
}
|
||||
|
||||
func TestRetrieveAll_VersionsAreIndependent(t *testing.T) {
|
||||
v20Retriever := &fakeRetriever{version: V20, err: errors.New("abe: inject failed")}
|
||||
got, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{
|
||||
retrieval := retrieveAll(context.Background(), Locator{}, []keyRetriever{
|
||||
&fakeRetriever{version: V10, key: v10Key},
|
||||
v20Retriever,
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "v20: abe: inject failed")
|
||||
assert.Equal(t, Set{V10: v10Key}, got, "a v20 failure keeps the v10 key")
|
||||
require.Error(t, retrieval.Err)
|
||||
assert.Contains(t, retrieval.Err.Error(), "v20: abe: inject failed")
|
||||
assert.Equal(t, Set{V10: v10Key}, retrieval.Keys, "a v20 failure keeps the v10 key")
|
||||
}
|
||||
|
||||
func TestRetrieveAll_ErrorOnlyWhenEveryRetrieverFails(t *testing.T) {
|
||||
first := errors.New("keychain: not found")
|
||||
second := errors.New("security command: denied")
|
||||
_, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{
|
||||
retrieval := retrieveAll(context.Background(), Locator{}, []keyRetriever{
|
||||
&fakeRetriever{version: V10, err: first},
|
||||
&fakeRetriever{version: V10, err: second},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, first)
|
||||
require.ErrorIs(t, err, second)
|
||||
require.Error(t, retrieval.Err)
|
||||
require.ErrorIs(t, retrieval.Err, first)
|
||||
require.ErrorIs(t, retrieval.Err, second)
|
||||
}
|
||||
|
||||
func TestRetrieveAll_NotApplicableIsSilent(t *testing.T) {
|
||||
got, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{
|
||||
retrieval := retrieveAll(context.Background(), Locator{}, []keyRetriever{
|
||||
&fakeRetriever{version: V10, err: errNotApplicable},
|
||||
&fakeRetriever{version: V20, err: errNotApplicable},
|
||||
&fakeRetriever{version: V11},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, got)
|
||||
require.NoError(t, retrieval.Err)
|
||||
assert.Empty(t, retrieval.Keys)
|
||||
}
|
||||
|
||||
func TestRetrieveAll_PassesTheLocator(t *testing.T) {
|
||||
retriever := &fakeRetriever{version: V10, key: v10Key}
|
||||
locator := Locator{LocalState: "/tmp/Local State", SecretLabel: "Chrome", Executable: "chrome.exe", ABE: ABEChromeBase}
|
||||
_, err := retrieveAll(context.Background(), locator, []keyRetriever{retriever})
|
||||
require.NoError(t, err)
|
||||
retrieval := retrieveAll(context.Background(), locator, []keyRetriever{retriever})
|
||||
require.NoError(t, retrieval.Err)
|
||||
assert.Equal(t, locator, retriever.gotLoc)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ A run is a fixed, one-way sequence of stages, and no stage reaches back:
|
||||
2. **Discover** — find each browser's data directories and their profiles.
|
||||
3. **Plan** — cross one directory's profiles with the requested categories into extractions, record why each skipped one cannot run, and list the files to copy.
|
||||
4. **Capture** — copy one directory's planned files into a temporary snapshot.
|
||||
5. **Extract** — parse the snapshot into records, fetching a secret only when a record needs it.
|
||||
5. **Extract** — parse the snapshot into records, fetching a secret once for its scope, and only when one of the scope's extractions needs it.
|
||||
6. **Export** — append each extraction's records to the output files.
|
||||
7. **Report** — summarize every outcome.
|
||||
|
||||
|
||||
+2
-2
@@ -9,11 +9,11 @@
|
||||
|
||||
## Scopes
|
||||
|
||||
Secrets live at different levels, so they are fetched at different levels: per data directory for Chromium's master keys, per profile for Firefox, whose key is derived from the profile's own files, and per run for the macOS login keychain.
|
||||
Secrets live at different levels, so they are fetched at different levels: per data directory for Chromium's master keys, per profile for Firefox, whose key is derived from the profile's own files, and per run for the macOS login keychain and the Firefox primary password the user supplies.
|
||||
|
||||
## Lazy retrieval
|
||||
|
||||
A secret is fetched by the first record that needs it, once per scope, and then reused. A run that asks only for history or bookmarks never retrieves a key and never prompts. A retrieval failure is reported once for its scope; records that needed the secret are still written, with that field empty, and count as `partial`.
|
||||
A secret is fetched once per scope, only when the scope has an extraction that needs it, and is then passed on as a plain value: a directory's master keys right after its files are captured, the login keychain at its first query. A run that asks only for history or bookmarks never retrieves a key and never prompts. Deciding per extraction rather than per record is what keeps each secret a value with one owner; the cost is an occasional retrieval, and on macOS a prompt, for a store that turns out to hold no encrypted row. A retrieval failure is reported once for its scope; records that needed the secret are still written, with that field empty, and count as `partial`.
|
||||
|
||||
## Key versions
|
||||
|
||||
|
||||
Reference in new issue
Block a user