diff --git a/browser/firefox/count.go b/browser/firefox/count.go new file mode 100644 index 0000000..b49e57d --- /dev/null +++ b/browser/firefox/count.go @@ -0,0 +1,65 @@ +package firefox + +import ( + "os" + + "github.com/tidwall/gjson" + + "github.com/moond4rk/hackbrowserdata/internal/sqlitex" +) + +// list --detail keeps today's counting queries until the switch-over, when it counts what the extractors emit. +const ( + firefoxCountCookieQuery = `SELECT COUNT(*) FROM moz_cookies` + firefoxCountHistoryQuery = `SELECT COUNT(*) FROM moz_places` + firefoxCountDownloadQuery = `SELECT COUNT(*) FROM + (SELECT place_id FROM moz_annos + INNER JOIN moz_places ON moz_annos.place_id=moz_places.id + GROUP BY place_id)` + firefoxCountBookmarkQuery = `SELECT COUNT(*) FROM moz_bookmarks + INNER JOIN moz_places ON moz_bookmarks.fk=moz_places.id` + firefoxCountLocalStorageQuery = `SELECT COUNT(*) FROM webappsstore2` +) + +func countPasswords(path string) (int, error) { + data, err := os.ReadFile(path) + if err != nil { + return 0, err + } + return len(gjson.GetBytes(data, "logins").Array()), nil +} + +func countCookies(path string) (int, error) { + return sqlitex.CountRows(path, true, firefoxCountCookieQuery) +} + +func countHistories(path string) (int, error) { + return sqlitex.CountRows(path, true, firefoxCountHistoryQuery) +} + +func countDownloads(path string) (int, error) { + return sqlitex.CountRows(path, true, firefoxCountDownloadQuery) +} + +func countBookmarks(path string) (int, error) { + return sqlitex.CountRows(path, true, firefoxCountBookmarkQuery) +} + +func countExtensions(path string) (int, error) { + data, err := os.ReadFile(path) + if err != nil { + return 0, err + } + + var count int + for _, v := range gjson.GetBytes(data, "addons").Array() { + if v.Get("location").String() == "app-profile" { + count++ + } + } + return count, nil +} + +func countLocalStorage(path string) (int, error) { + return sqlitex.CountRows(path, true, firefoxCountLocalStorageQuery) +} diff --git a/browser/firefox/count_test.go b/browser/firefox/count_test.go new file mode 100644 index 0000000..9018b0a --- /dev/null +++ b/browser/firefox/count_test.go @@ -0,0 +1,127 @@ +package firefox + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCountBookmarks(t *testing.T) { + path := setupMozBookmarkDB(t) + + count, err := countBookmarks(path) + require.NoError(t, err) + assert.Equal(t, 2, count) +} + +func TestCountBookmarks_Empty(t *testing.T) { + path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozBookmarksSchema}) + + count, err := countBookmarks(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} + +func TestCountCookies(t *testing.T) { + path := setupMozCookieDB(t) + + count, err := countCookies(path) + require.NoError(t, err) + assert.Equal(t, 2, count) +} + +func TestCountCookies_Empty(t *testing.T) { + path := createTestDB(t, "cookies.sqlite", []string{mozCookiesSchema}) + + count, err := countCookies(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} + +func TestCountDownloads(t *testing.T) { + path := setupMozDownloadDB(t) + + count, err := countDownloads(path) + require.NoError(t, err) + assert.Equal(t, 2, count) +} + +func TestCountDownloads_Empty(t *testing.T) { + path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozAnnosSchema}) + + count, err := countDownloads(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} + +func TestCountExtensions(t *testing.T) { + path := setupMozExtensionJSON(t) + + count, err := countExtensions(path) + require.NoError(t, err) + assert.Equal(t, 2, count) // system addon filtered out +} + +func TestCountExtensions_Empty(t *testing.T) { + path := createTestJSON(t, "extensions.json", `{"addons": []}`) + + count, err := countExtensions(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} + +func TestCountHistories(t *testing.T) { + path := setupMozHistoryDB(t) + + count, err := countHistories(path) + require.NoError(t, err) + assert.Equal(t, 3, count) +} + +func TestCountHistories_Empty(t *testing.T) { + path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema}) + + count, err := countHistories(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} + +func TestCountLocalStorage(t *testing.T) { + path := setupWebappsDB(t) + + count, err := countLocalStorage(path) + require.NoError(t, err) + assert.Equal(t, 3, count) +} + +func TestCountLocalStorage_Empty(t *testing.T) { + path := createTestDB(t, "webappsstore.sqlite", []string{webappsstore2Schema}) + + count, err := countLocalStorage(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} + +func TestCountPasswords(t *testing.T) { + json := `{ + "logins": [ + {"hostname": "https://a.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 1000}, + {"hostname": "https://b.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 2000}, + {"hostname": "https://c.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 3000} + ] + }` + path := createTestJSON(t, "logins.json", json) + + count, err := countPasswords(path) + require.NoError(t, err) + assert.Equal(t, 3, count) +} + +func TestCountPasswords_Empty(t *testing.T) { + path := createTestJSON(t, "logins.json", `{"logins": []}`) + + count, err := countPasswords(path) + require.NoError(t, err) + assert.Equal(t, 0, count) +} diff --git a/browser/firefox/firefox.go b/browser/firefox/firefox.go index 58034d6..34ea028 100644 --- a/browser/firefox/firefox.go +++ b/browser/firefox/firefox.go @@ -1,8 +1,6 @@ package firefox import ( - "errors" - "fmt" "os" "path/filepath" @@ -77,36 +75,6 @@ func (b *Browser) CountEntries(categories []category.Category) ([]types.CountRes return results, nil } -// retrieveMasterKey reads key4.db and derives the master key using NSS. -// If loginsPath is non-empty, the derived key is validated against actual -// login data to ensure the correct candidate is selected. -func retrieveMasterKey(key4Path, loginsPath string) ([]byte, error) { - k4, err := readKey4DB(key4Path) - if err != nil { - return nil, err - } - - keys, err := k4.deriveKeys() - if err != nil { - return nil, err - } - if len(keys) == 0 { - return nil, errors.New("no valid master key candidates in key4.db") - } - - // No logins to validate against — return the first derived key. - if loginsPath == "" { - return keys[0], nil - } - - // Validate against actual login data. - if key := validateKeyWithLogins(keys, loginsPath); key != nil { - return key, nil - } - - return nil, fmt.Errorf("derived %d key(s) but none could decrypt logins", len(keys)) -} - // resolvedPath holds the absolute path and type for a discovered source. type resolvedPath struct { absPath string diff --git a/browser/firefox/profile.go b/browser/firefox/profile.go index da33202..7ec75a2 100644 --- a/browser/firefox/profile.go +++ b/browser/firefox/profile.go @@ -1,16 +1,23 @@ package firefox import ( - "fmt" + "context" + "os" "path/filepath" "github.com/moond4rk/hackbrowserdata/filemanager" + ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser" + ifirefox "github.com/moond4rk/hackbrowserdata/internal/browser/firefox" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" "github.com/moond4rk/hackbrowserdata/types" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) +// snapshotDirID names the one user data dir in a profile's private snapshot, whose root is the profile dir itself. +const snapshotDirID = "profile" + // profile is one Firefox profile — the leaf extraction unit. Unlike Chromium, // each Firefox profile owns its own master key (derived from its key4.db). type profile struct { @@ -28,34 +35,97 @@ func (p *profile) name() string { func (p *profile) label() string { return p.browserName + "/" + p.name() } -// extract copies the profile's source files to a temp directory, derives the -// per-profile master key, and extracts the requested categories. +// extract captures the profile's sources into a private snapshot and runs the Firefox base's extractors on it. func (p *profile) extract(categories []category.Category) *types.BrowserData { - session, err := filemanager.NewSession() - if err != nil { - log.Debugf("new session for %s: %v", p.label(), err) - return &types.BrowserData{} - } - defer session.Cleanup() - - tempPaths := p.acquireFiles(session, categories) - - masterKey, err := p.getMasterKey(session, tempPaths) - if err != nil { - log.Debugf("get master key for %s: %v", p.label(), err) - } - data := &types.BrowserData{} + d, err := snapshot.Temp() + if err != nil { + log.Debugf("new snapshot for %s: %v", p.label(), err) + return data + } + defer func() { + if err := d.Close(); err != nil { + log.Debugf("remove snapshot for %s: %v", p.label(), err) + } + }() + + extractors := ifirefox.Extractors(ibrowser.UserDataDir{}, ibrowser.Profile{}) + ctx := context.Background() + if err := d.Capture(ctx, p.snapshotFiles(extractors, categories)); err != nil { + log.Debugf("capture %s: %v", p.label(), err) + return data + } + ps := ibrowser.NewProfileSnapshot(d.Snapshot(snapshotDirID), ibrowser.Profile{Name: p.name()}, nil) + out := &dataCollector{data: data, label: p.label()} for _, cat := range categories { - path, ok := tempPaths[cat] - if !ok { + ex, ok := extractors[cat] + if _, found := p.sourcePaths[cat]; !ok || !found { continue } - p.extractCategory(data, cat, masterKey, path) + if err := ex.Extract(ctx, ps, out); err != nil { + log.Debugf("extract %s for %s: %v", cat, p.label(), err) + } } return data } +// snapshotFiles lists, once each, the first candidate on disk of every source the categories read. +func (p *profile) snapshotFiles(extractors ibrowser.Extractors, categories []category.Category) []snapshot.File { + var files []snapshot.File + seen := make(map[string]bool) + for _, cat := range categories { + if _, found := p.sourcePaths[cat]; !found { + continue + } + for _, src := range extractors[cat].Sources { + rel, ok := firstOnDisk(p.profileDir, src) + if !ok || seen[rel] { + continue + } + seen[rel] = true + files = append(files, snapshot.File{DirID: snapshotDirID, From: p.profileDir, Rel: rel, IsDir: src.IsDir}) + } + } + return files +} + +func firstOnDisk(dir string, src ibrowser.Source) (string, bool) { + for _, rel := range src.Paths { + info, err := os.Stat(filepath.Join(dir, filepath.FromSlash(rel))) + if err == nil && info.IsDir() == src.IsDir { + return rel, true + } + } + return "", false +} + +// dataCollector files the records the Firefox base hands back into today's per-category slices. +type dataCollector struct { + data *types.BrowserData + label string +} + +func (c *dataCollector) Add(r record.Record) { + switch v := r.(type) { + case *record.Login: + c.data.Passwords = append(c.data.Passwords, *v) + case *record.Cookie: + c.data.Cookies = append(c.data.Cookies, *v) + case *record.Bookmark: + c.data.Bookmarks = append(c.data.Bookmarks, *v) + case *record.History: + c.data.Histories = append(c.data.Histories, *v) + case *record.Download: + c.data.Downloads = append(c.data.Downloads, *v) + case *record.Extension: + c.data.Extensions = append(c.data.Extensions, *v) + case *record.LocalStorage: + c.data.LocalStorage = append(c.data.LocalStorage, *v) + } +} + +func (c *dataCollector) Fail(err error) { log.Debugf("%s: %v", c.label, err) } + func (p *profile) count(categories []category.Category) map[category.Category]int { session, err := filemanager.NewSession() if err != nil { @@ -93,51 +163,6 @@ func (p *profile) acquireFiles(session *filemanager.Session, categories []catego return tempPaths } -// getMasterKey retrieves the Firefox master encryption key from this profile's -// key4.db. The key is derived via NSS ASN1 PBE decryption (platform-agnostic). -// If logins.json was already acquired by acquireFiles, the derived key is -// validated by attempting to decrypt an actual login entry. -func (p *profile) getMasterKey(session *filemanager.Session, tempPaths map[category.Category]string) ([]byte, error) { - key4Src := filepath.Join(p.profileDir, "key4.db") - if !fileutil.FileExists(key4Src) { - return nil, nil - } - key4Dst := filepath.Join(session.TempDir(), "key4.db") - if err := session.Acquire(key4Src, key4Dst, false); err != nil { - return nil, fmt.Errorf("acquire key4.db: %w", err) - } - - // logins.json is already acquired by acquireFiles as the Password source; - // reuse it for master key validation if available. - loginsPath := tempPaths[category.Password] - return retrieveMasterKey(key4Dst, loginsPath) -} - -func (p *profile) extractCategory(data *types.BrowserData, cat category.Category, masterKey []byte, path string) { - var err error - switch cat { - case category.Password: - data.Passwords, err = extractPasswords(masterKey, path) - case category.Cookie: - data.Cookies, err = extractCookies(path) - case category.History: - data.Histories, err = extractHistories(path) - case category.Download: - data.Downloads, err = extractDownloads(path) - case category.Bookmark: - data.Bookmarks, err = extractBookmarks(path) - case category.Extension: - data.Extensions, err = extractExtensions(path) - case category.LocalStorage: - data.LocalStorage, err = extractLocalStorage(path) - case category.CreditCard, category.SessionStorage: - // Firefox does not support CreditCard or SessionStorage extraction. - } - if err != nil { - log.Debugf("extract %s for %s: %v", cat, p.label(), err) - } -} - func (p *profile) countCategory(cat category.Category, path string) int { var count int var err error diff --git a/browser/firefox/profile_test.go b/browser/firefox/profile_test.go index 5ce5baa..7a162ad 100644 --- a/browser/firefox/profile_test.go +++ b/browser/firefox/profile_test.go @@ -7,7 +7,6 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/types" ) func TestCountCategory(t *testing.T) { @@ -42,86 +41,23 @@ func TestCountCategory(t *testing.T) { }) } -// --------------------------------------------------------------------------- -// extractCategory -// --------------------------------------------------------------------------- +// extract runs the Firefox base's extractors on a private snapshot of the profile. +func TestExtract(t *testing.T) { + profileDir := t.TempDir() + installFile(t, profileDir, setupMozHistoryDB(t), "places.sqlite") + installFile(t, profileDir, setupMozCookieDB(t), "cookies.sqlite") + installFile(t, profileDir, setupMozExtensionJSON(t), "extensions.json") + p := &profile{profileDir: profileDir, browserName: "Firefox", sourcePaths: resolveSourcePaths(firefoxSources, profileDir)} -// TestExtractCategory verifies that the switch dispatch works for each category. -func TestExtractCategory(t *testing.T) { - t.Run("History", func(t *testing.T) { - path := createTestDB(t, "places.sqlite", - []string{mozPlacesSchema}, - insertMozPlace(1, "https://example.com", "Example", 3, 1000000), - insertMozPlace(2, "https://go.dev", "Go", 1, 2000000), - ) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.History, nil, path) - - require.Len(t, data.Histories, 2) - assert.ElementsMatch(t, []int{3, 1}, []int{data.Histories[0].VisitCount, data.Histories[1].VisitCount}) - }) - - t.Run("Cookie", func(t *testing.T) { - path := createTestDB(t, "cookies.sqlite", - []string{mozCookiesSchema}, - insertMozCookie("session", "abc", ".example.com", "/", 1000000000000, 0, 0, 0), - ) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.Cookie, nil, path) - - require.Len(t, data.Cookies, 1) - assert.Equal(t, "session", data.Cookies[0].Name) - assert.Equal(t, "abc", data.Cookies[0].Value) // Firefox cookies are not encrypted - }) - - t.Run("Bookmark", func(t *testing.T) { - path := createTestDB(t, "places.sqlite", - []string{mozPlacesSchema, mozBookmarksSchema}, - insertMozPlace(1, "https://github.com", "GitHub", 1, 1000000), - insertMozBookmark(1, 1, 1, "GitHub", 1000000), - ) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.Bookmark, nil, path) - - require.Len(t, data.Bookmarks, 1) - assert.Equal(t, "GitHub", data.Bookmarks[0].Name) - }) - - t.Run("Extension", func(t *testing.T) { - path := createTestJSON(t, "extensions.json", `{ - "addons": [ - { - "id": "ublock@example.com", - "location": "app-profile", - "active": true, - "version": "1.0", - "defaultLocale": {"name": "uBlock Origin", "description": "Ad blocker"} - }, - { - "id": "system@mozilla.com", - "location": "app-system-defaults", - "active": true - } - ] - }`) - p := &profile{} - data := &types.BrowserData{} - p.extractCategory(data, category.Extension, nil, path) - - require.Len(t, data.Extensions, 1) // system extension skipped - assert.Equal(t, "uBlock Origin", data.Extensions[0].Name) - }) - - t.Run("UnsupportedCategory", func(t *testing.T) { - p := &profile{} - data := &types.BrowserData{} - // CreditCard and SessionStorage are not supported by Firefox - p.extractCategory(data, category.CreditCard, nil, "unused") - p.extractCategory(data, category.SessionStorage, nil, "unused") - assert.Empty(t, data.CreditCards) - assert.Empty(t, data.SessionStorage) + data := p.extract([]category.Category{ + category.History, category.Cookie, category.Extension, category.CreditCard, category.SessionStorage, }) + require.Len(t, data.Histories, 3) + visits := []int{data.Histories[0].VisitCount, data.Histories[1].VisitCount, data.Histories[2].VisitCount} + assert.ElementsMatch(t, []int{100, 50, 200}, visits) + require.Len(t, data.Cookies, 2) + assert.Equal(t, "abc123", data.Cookies[0].Value) // Firefox cookies are not encrypted + assert.Len(t, data.Extensions, 2) // the system add-on is skipped + assert.Empty(t, data.CreditCards) + assert.Empty(t, data.SessionStorage) } diff --git a/browser/firefox/testutil_test.go b/browser/firefox/testutil_test.go index e3a5b69..8c5ea67 100644 --- a/browser/firefox/testutil_test.go +++ b/browser/firefox/testutil_test.go @@ -173,3 +173,83 @@ func createTestJSON(t *testing.T, name, content string) string { require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) return path } + +func setupMozBookmarkDB(t *testing.T) string { + t.Helper() + return createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozBookmarksSchema}, + insertMozPlace(1, "https://go.dev", "Go", 0, 0), + insertMozPlace(2, "https://github.com", "GitHub", 0, 0), + insertMozBookmark(1, 1, 1, "Go Website", 1700000000000000), + insertMozBookmark(2, 2, 1, "GitHub", 1710000000000000), + ) +} + +func setupMozCookieDB(t *testing.T) string { + t.Helper() + return createTestDB(t, "cookies.sqlite", []string{mozCookiesSchema}, + insertMozCookie("session", "abc123", ".example.com", "/", 1700000000000000, 1800000000, 1, 1), + insertMozCookie("token", "xyz789", ".new.com", "/api", 1710000000000000, 1810000000, 1, 0), + ) +} + +func setupMozDownloadDB(t *testing.T) string { + t.Helper() + return createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozAnnosSchema}, + insertMozPlace(1, "https://example.com/old.zip", "Old File", 0, 0), + insertMozPlace(2, "https://example.com/new.pdf", "New File", 0, 0), + insertMozAnno(1, "/tmp/old.zip", 1700000000000000), + insertMozAnno(2, "/tmp/new.pdf", 1710000000000000), + ) +} + +func setupMozExtensionJSON(t *testing.T) string { + t.Helper() + return createTestJSON(t, "extensions.json", `{ + "addons": [ + { + "id": "ublock@gorhill.org", + "location": "app-profile", + "version": "1.52.0", + "active": true, + "defaultLocale": { + "name": "uBlock Origin", + "description": "An efficient blocker" + } + }, + { + "id": "system@mozilla.org", + "location": "app-system-defaults", + "version": "1.0", + "defaultLocale": {"name": "System Addon"} + }, + { + "id": "bitwarden@bitwarden.com", + "location": "app-profile", + "version": "2024.1.0", + "active": true, + "defaultLocale": { + "name": "Bitwarden", + "description": "Password manager" + } + } + ] + }`) +} + +func setupMozHistoryDB(t *testing.T) string { + t.Helper() + return createTestDB(t, "places.sqlite", []string{mozPlacesSchema}, + insertMozPlace(1, "https://github.com", "GitHub", 100, 1700000000000000), + insertMozPlace(2, "https://go.dev", "Go", 50, 1710000000000000), + insertMozPlace(3, "https://example.com", "Example", 200, 1690000000000000), + ) +} + +func setupWebappsDB(t *testing.T) string { + t.Helper() + return createTestDB(t, "webappsstore.sqlite", []string{webappsstore2Schema}, + insertWebappsstore("moc.buhtig.:https:443", "theme", "dark"), + insertWebappsstore("moc.buhtig.:https:443", "lang", "en"), + insertWebappsstore("moc.elpmaxe.:http:8080", "token", "abc123"), + ) +} diff --git a/cmd/hack-browser-data/pipeline_golden_test.go b/cmd/hack-browser-data/pipeline_golden_test.go index f4bf2dd..7944822 100644 --- a/cmd/hack-browser-data/pipeline_golden_test.go +++ b/cmd/hack-browser-data/pipeline_golden_test.go @@ -30,6 +30,17 @@ func TestPipelineGolden(t *testing.T) { }) } +func TestPipelineGoldenFirefox(t *testing.T) { + home := t.TempDir() + def, ok := ibrowser.Lookup("firefox") + require.True(t, ok) + firefoxFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0]))) + + assertExtractGoldens(t, "extract-firefox", func(t *testing.T, format string) string { + return pipelineGoldenRun(t, home, nil, format) + }) +} + func pipelineGoldenRun(t *testing.T, home string, keys map[ibrowser.DirID]masterkey.Set, format string) string { t.Helper() out := t.TempDir() diff --git a/internal/app/discover.go b/internal/app/discover.go index c524442..0671079 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -3,6 +3,7 @@ package app import ( "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/browser/firefox" ) // Discovery is what Discover found: the user data dirs, and an error result for each browser whose data could not be @@ -38,8 +39,10 @@ func discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserData switch def.Base { case browser.Chromium: return chromium.Discover(def, opts) + case browser.Firefox: + return firefox.Discover(def, opts) default: - return nil, nil // Firefox and Safari are not on the pipeline yet + return nil, nil // Safari is not on the pipeline yet } } @@ -47,6 +50,8 @@ func extractorsOf(dir browser.UserDataDir, p browser.Profile) browser.Extractors switch dir.Def.Base { case browser.Chromium: return chromium.Extractors(dir, p) + case browser.Firefox: + return firefox.Extractors(dir, p) default: return nil } diff --git a/browser/firefox/extract_bookmark.go b/internal/browser/firefox/extract_bookmark.go similarity index 60% rename from browser/firefox/extract_bookmark.go rename to internal/browser/firefox/extract_bookmark.go index a51a39b..286d2e6 100644 --- a/browser/firefox/extract_bookmark.go +++ b/internal/browser/firefox/extract_bookmark.go @@ -3,19 +3,16 @@ package firefox import ( "database/sql" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" ) -const ( - firefoxBookmarkQuery = `SELECT id, url, type, dateAdded, COALESCE(title, '') - FROM (SELECT * FROM moz_bookmarks INNER JOIN moz_places ON moz_bookmarks.fk=moz_places.id)` - firefoxCountBookmarkQuery = `SELECT COUNT(*) FROM moz_bookmarks - INNER JOIN moz_places ON moz_bookmarks.fk=moz_places.id` -) +const firefoxBookmarkQuery = `SELECT id, url, type, dateAdded, COALESCE(title, '') + FROM (SELECT * FROM moz_bookmarks INNER JOIN moz_places ON moz_bookmarks.fk=moz_places.id)` -func extractBookmarks(path string) ([]record.Bookmark, error) { +func extractBookmarks(path string, out browser.Collector) error { bookmarks, err := sqlitex.QueryRows(path, true, firefoxBookmarkQuery, func(rows *sql.Rows) (record.Bookmark, error) { var id, dateAdded int64 @@ -32,9 +29,10 @@ func extractBookmarks(path string) ([]record.Bookmark, error) { }, nil }) if err != nil { - return nil, err + return err } - return bookmarks, nil + emit(out, bookmarks) + return nil } func bookmarkType(bt int64) string { @@ -45,7 +43,3 @@ func bookmarkType(bt int64) string { return "folder" } } - -func countBookmarks(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountBookmarkQuery) -} diff --git a/browser/firefox/extract_bookmark_test.go b/internal/browser/firefox/extract_bookmark_test.go similarity index 69% rename from browser/firefox/extract_bookmark_test.go rename to internal/browser/firefox/extract_bookmark_test.go index 0f62b57..0fb5f61 100644 --- a/browser/firefox/extract_bookmark_test.go +++ b/internal/browser/firefox/extract_bookmark_test.go @@ -5,6 +5,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func setupMozBookmarkDB(t *testing.T) string { @@ -20,7 +22,9 @@ func setupMozBookmarkDB(t *testing.T) string { func TestExtractBookmarks(t *testing.T) { path := setupMozBookmarkDB(t) - got, err := extractBookmarks(path) + var out testCollector + err := extractBookmarks(path, &out) + got := collected[record.Bookmark](t, &out) require.NoError(t, err) require.Len(t, got, 2) @@ -33,19 +37,3 @@ func TestExtractBookmarks(t *testing.T) { assert.Equal(t, "url", got[1].Folder) // type=1 → "url" assert.False(t, got[1].CreatedAt.IsZero()) } - -func TestCountBookmarks(t *testing.T) { - path := setupMozBookmarkDB(t) - - count, err := countBookmarks(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountBookmarks_Empty(t *testing.T) { - path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozBookmarksSchema}) - - count, err := countBookmarks(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} diff --git a/browser/firefox/extract_cookie.go b/internal/browser/firefox/extract_cookie.go similarity index 76% rename from browser/firefox/extract_cookie.go rename to internal/browser/firefox/extract_cookie.go index fe1c6ce..a9697fe 100644 --- a/browser/firefox/extract_cookie.go +++ b/internal/browser/firefox/extract_cookie.go @@ -3,18 +3,16 @@ package firefox import ( "database/sql" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" ) -const ( - firefoxCookieQuery = `SELECT name, value, host, path, - creationTime, expiry, isSecure, isHttpOnly, sameSite FROM moz_cookies` - firefoxCountCookieQuery = `SELECT COUNT(*) FROM moz_cookies` -) +const firefoxCookieQuery = `SELECT name, value, host, path, + creationTime, expiry, isSecure, isHttpOnly, sameSite FROM moz_cookies` -func extractCookies(path string) ([]record.Cookie, error) { +func extractCookies(path string, out browser.Collector) error { cookies, err := sqlitex.QueryRows(path, true, firefoxCookieQuery, func(rows *sql.Rows) (record.Cookie, error) { var ( @@ -54,11 +52,8 @@ func extractCookies(path string) ([]record.Cookie, error) { }, nil }) if err != nil { - return nil, err + return err } - return cookies, nil -} - -func countCookies(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountCookieQuery) + emit(out, cookies) + return nil } diff --git a/browser/firefox/extract_cookie_test.go b/internal/browser/firefox/extract_cookie_test.go similarity index 74% rename from browser/firefox/extract_cookie_test.go rename to internal/browser/firefox/extract_cookie_test.go index fee2c80..9f3d4ea 100644 --- a/browser/firefox/extract_cookie_test.go +++ b/internal/browser/firefox/extract_cookie_test.go @@ -5,6 +5,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func setupMozCookieDB(t *testing.T) string { @@ -18,7 +20,9 @@ func setupMozCookieDB(t *testing.T) string { func TestExtractCookies(t *testing.T) { path := setupMozCookieDB(t) - got, err := extractCookies(path) + var out testCollector + err := extractCookies(path, &out) + got := collected[record.Cookie](t, &out) require.NoError(t, err) require.Len(t, got, 2) @@ -38,19 +42,3 @@ func TestExtractCookies(t *testing.T) { assert.Equal(t, "abc123", got[0].Value) assert.True(t, got[0].IsHTTPOnly) } - -func TestCountCookies(t *testing.T) { - path := setupMozCookieDB(t) - - count, err := countCookies(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountCookies_Empty(t *testing.T) { - path := createTestDB(t, "cookies.sqlite", []string{mozCookiesSchema}) - - count, err := countCookies(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} diff --git a/browser/firefox/extract_download.go b/internal/browser/firefox/extract_download.go similarity index 66% rename from browser/firefox/extract_download.go rename to internal/browser/firefox/extract_download.go index f84a59d..381050c 100644 --- a/browser/firefox/extract_download.go +++ b/internal/browser/firefox/extract_download.go @@ -6,22 +6,17 @@ import ( "github.com/tidwall/gjson" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" ) -const ( - firefoxDownloadQuery = `SELECT place_id, GROUP_CONCAT(content), url, dateAdded - FROM (SELECT * FROM moz_annos INNER JOIN moz_places ON moz_annos.place_id=moz_places.id) - t GROUP BY place_id` - firefoxCountDownloadQuery = `SELECT COUNT(*) FROM - (SELECT place_id FROM moz_annos - INNER JOIN moz_places ON moz_annos.place_id=moz_places.id - GROUP BY place_id)` -) +const firefoxDownloadQuery = `SELECT place_id, GROUP_CONCAT(content), url, dateAdded + FROM (SELECT * FROM moz_annos INNER JOIN moz_places ON moz_annos.place_id=moz_places.id) + t GROUP BY place_id` -func extractDownloads(path string) ([]record.Download, error) { +func extractDownloads(path string, out browser.Collector) error { downloads, err := sqlitex.QueryRows(path, true, firefoxDownloadQuery, func(rows *sql.Rows) (record.Download, error) { var placeID, dateAdded int64 @@ -50,11 +45,8 @@ func extractDownloads(path string) ([]record.Download, error) { return entry, nil }) if err != nil { - return nil, err + return err } - return downloads, nil -} - -func countDownloads(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountDownloadQuery) + emit(out, downloads) + return nil } diff --git a/browser/firefox/extract_download_test.go b/internal/browser/firefox/extract_download_test.go similarity index 69% rename from browser/firefox/extract_download_test.go rename to internal/browser/firefox/extract_download_test.go index 29f264d..21f2e9a 100644 --- a/browser/firefox/extract_download_test.go +++ b/internal/browser/firefox/extract_download_test.go @@ -5,6 +5,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func setupMozDownloadDB(t *testing.T) string { @@ -20,7 +22,9 @@ func setupMozDownloadDB(t *testing.T) string { func TestExtractDownloads(t *testing.T) { path := setupMozDownloadDB(t) - got, err := extractDownloads(path) + var out testCollector + err := extractDownloads(path, &out) + got := collected[record.Download](t, &out) require.NoError(t, err) require.Len(t, got, 2) @@ -32,19 +36,3 @@ func TestExtractDownloads(t *testing.T) { assert.Equal(t, "/tmp/new.pdf", got[1].TargetPath) assert.False(t, got[1].StartTime.IsZero()) } - -func TestCountDownloads(t *testing.T) { - path := setupMozDownloadDB(t) - - count, err := countDownloads(path) - require.NoError(t, err) - assert.Equal(t, 2, count) -} - -func TestCountDownloads_Empty(t *testing.T) { - path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozAnnosSchema}) - - count, err := countDownloads(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} diff --git a/browser/firefox/extract_extension.go b/internal/browser/firefox/extract_extension.go similarity index 68% rename from browser/firefox/extract_extension.go rename to internal/browser/firefox/extract_extension.go index f1b345a..6b19602 100644 --- a/browser/firefox/extract_extension.go +++ b/internal/browser/firefox/extract_extension.go @@ -5,13 +5,14 @@ import ( "github.com/tidwall/gjson" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" ) -func extractExtensions(path string) ([]record.Extension, error) { +func extractExtensions(path string, out browser.Collector) error { data, err := os.ReadFile(path) if err != nil { - return nil, err + return err } var extensions []record.Extension @@ -31,21 +32,6 @@ func extractExtensions(path string) ([]record.Extension, error) { Enabled: v.Get("active").Bool(), }) } - - return extensions, nil -} - -func countExtensions(path string) (int, error) { - data, err := os.ReadFile(path) - if err != nil { - return 0, err - } - - var count int - for _, v := range gjson.GetBytes(data, "addons").Array() { - if v.Get("location").String() == "app-profile" { - count++ - } - } - return count, nil + emit(out, extensions) + return nil } diff --git a/browser/firefox/extract_extension_test.go b/internal/browser/firefox/extract_extension_test.go similarity index 75% rename from browser/firefox/extract_extension_test.go rename to internal/browser/firefox/extract_extension_test.go index 96bf88f..f34216f 100644 --- a/browser/firefox/extract_extension_test.go +++ b/internal/browser/firefox/extract_extension_test.go @@ -5,6 +5,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func setupMozExtensionJSON(t *testing.T) string { @@ -44,7 +46,9 @@ func setupMozExtensionJSON(t *testing.T) string { func TestExtractExtensions(t *testing.T) { path := setupMozExtensionJSON(t) - got, err := extractExtensions(path) + var out testCollector + err := extractExtensions(path, &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 2) // system addon filtered out @@ -59,25 +63,11 @@ func TestExtractExtensions(t *testing.T) { assert.False(t, ids["system@mozilla.org"]) } -func TestCountExtensions(t *testing.T) { - path := setupMozExtensionJSON(t) - - count, err := countExtensions(path) - require.NoError(t, err) - assert.Equal(t, 2, count) // system addon filtered out -} - -func TestCountExtensions_Empty(t *testing.T) { - path := createTestJSON(t, "extensions.json", `{"addons": []}`) - - count, err := countExtensions(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - func TestExtractExtensions_EmptyAddons(t *testing.T) { path := createTestJSON(t, "extensions.json", `{"addons": []}`) - got, err := extractExtensions(path) + var out testCollector + err := extractExtensions(path, &out) + got := collected[record.Extension](t, &out) require.NoError(t, err) assert.Empty(t, got) } diff --git a/browser/firefox/extract_history.go b/internal/browser/firefox/extract_history.go similarity index 63% rename from browser/firefox/extract_history.go rename to internal/browser/firefox/extract_history.go index 9aa33f8..5c4c65e 100644 --- a/browser/firefox/extract_history.go +++ b/internal/browser/firefox/extract_history.go @@ -3,18 +3,16 @@ package firefox import ( "database/sql" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" "github.com/moond4rk/hackbrowserdata/internal/timeconv" ) -const ( - firefoxHistoryQuery = `SELECT url, COALESCE(last_visit_date, 0), - COALESCE(title, ''), visit_count FROM moz_places` - firefoxCountHistoryQuery = `SELECT COUNT(*) FROM moz_places` -) +const firefoxHistoryQuery = `SELECT url, COALESCE(last_visit_date, 0), + COALESCE(title, ''), visit_count FROM moz_places` -func extractHistories(path string) ([]record.History, error) { +func extractHistories(path string, out browser.Collector) error { histories, err := sqlitex.QueryRows(path, true, firefoxHistoryQuery, func(rows *sql.Rows) (record.History, error) { var url, title string @@ -31,11 +29,8 @@ func extractHistories(path string) ([]record.History, error) { }, nil }) if err != nil { - return nil, err + return err } - return histories, nil -} - -func countHistories(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountHistoryQuery) + emit(out, histories) + return nil } diff --git a/browser/firefox/extract_history_test.go b/internal/browser/firefox/extract_history_test.go similarity index 75% rename from browser/firefox/extract_history_test.go rename to internal/browser/firefox/extract_history_test.go index 2b75e55..82cb8e4 100644 --- a/browser/firefox/extract_history_test.go +++ b/internal/browser/firefox/extract_history_test.go @@ -5,6 +5,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func setupMozHistoryDB(t *testing.T) string { @@ -19,7 +21,9 @@ func setupMozHistoryDB(t *testing.T) string { func TestExtractHistories(t *testing.T) { path := setupMozHistoryDB(t) - got, err := extractHistories(path) + var out testCollector + err := extractHistories(path, &out) + got := collected[record.History](t, &out) require.NoError(t, err) require.Len(t, got, 3) @@ -34,22 +38,6 @@ func TestExtractHistories(t *testing.T) { assert.False(t, got[1].LastVisit.IsZero()) } -func TestCountHistories(t *testing.T) { - path := setupMozHistoryDB(t) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountHistories_Empty(t *testing.T) { - path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema}) - - count, err := countHistories(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - func TestExtractHistories_NullFields(t *testing.T) { path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema}, // last_visit_date=NULL, title=NULL — COALESCE should handle @@ -57,7 +45,9 @@ func TestExtractHistories_NullFields(t *testing.T) { VALUES (1, 'https://null.test', 1, '', 'g1', 0)`, ) - got, err := extractHistories(path) + var out testCollector + err := extractHistories(path, &out) + got := collected[record.History](t, &out) require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "https://null.test", got[0].URL) diff --git a/browser/firefox/extract_password.go b/internal/browser/firefox/extract_password.go similarity index 64% rename from browser/firefox/extract_password.go rename to internal/browser/firefox/extract_password.go index 42e8b80..892a321 100644 --- a/browser/firefox/extract_password.go +++ b/internal/browser/firefox/extract_password.go @@ -7,20 +7,12 @@ import ( "github.com/tidwall/gjson" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/crypto" - "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/timeconv" ) -func countPasswords(path string) (int, error) { - data, err := os.ReadFile(path) - if err != nil { - return 0, err - } - return len(gjson.GetBytes(data, "logins").Array()), nil -} - // decryptPBE combines base64 decode + ASN1 PBE parse + decrypt into one call. func decryptPBE(encoded string, masterKey []byte) ([]byte, error) { raw, err := base64.StdEncoding.DecodeString(encoded) @@ -38,30 +30,27 @@ func decryptPBE(encoded string, masterKey []byte) ([]byte, error) { return plaintext, nil } -func extractPasswords(masterKey []byte, path string) ([]record.Login, error) { +func extractPasswords(masterKey func() []byte, path string, out browser.Collector) error { data, err := os.ReadFile(path) if err != nil { - return nil, err + return err } var logins []record.Login - var decryptFails int - var lastErr error for _, v := range gjson.GetBytes(data, "logins").Array() { url := v.Get("formSubmitURL").String() if url == "" { url = v.Get("hostname").String() } - user, err := decryptPBE(v.Get("encryptedUsername").String(), masterKey) + key := masterKey() + user, err := decryptPBE(v.Get("encryptedUsername").String(), key) if err != nil { - decryptFails++ - lastErr = err + out.Fail(fmt.Errorf("decrypt username for %s: %w", url, err)) } - pwd, err := decryptPBE(v.Get("encryptedPassword").String(), masterKey) + pwd, err := decryptPBE(v.Get("encryptedPassword").String(), key) if err != nil { - decryptFails++ - lastErr = err + out.Fail(fmt.Errorf("decrypt password for %s: %w", url, err)) } logins = append(logins, record.Login{ @@ -72,8 +61,6 @@ func extractPasswords(masterKey []byte, path string) ([]record.Login, error) { Store: record.StoreLocal, }) } - if decryptFails > 0 { - log.Debugf("decrypt firefox login fields: %d failed: %v", decryptFails, lastErr) - } - return logins, nil + emit(out, logins) + return nil } diff --git a/browser/firefox/extract_password_test.go b/internal/browser/firefox/extract_password_test.go similarity index 75% rename from browser/firefox/extract_password_test.go rename to internal/browser/firefox/extract_password_test.go index e220014..ece7e54 100644 --- a/browser/firefox/extract_password_test.go +++ b/internal/browser/firefox/extract_password_test.go @@ -9,6 +9,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) // These values are from crypto/asn1pbe_test.go loginPBETestCases. @@ -17,6 +19,8 @@ const loginPBEHex = "303b0410f8000000000000000000000000000001301506092a864886f70 var testGlobalSalt = bytes.Repeat([]byte("moond4rk"), 3) // 24 bytes +func fixedKey(key []byte) func() []byte { return func() []byte { return key } } + func loginPBEBase64(t *testing.T) string { t.Helper() raw, err := hex.DecodeString(loginPBEHex) @@ -42,7 +46,9 @@ func TestExtractPasswords(t *testing.T) { path := createTestJSON(t, "logins.json", json) - got, err := extractPasswords(testGlobalSalt, path) + var out testCollector + err := extractPasswords(fixedKey(testGlobalSalt), path, &out) + got := collected[record.Login](t, &out) require.NoError(t, err) require.Len(t, got, 1) @@ -53,29 +59,6 @@ func TestExtractPasswords(t *testing.T) { assert.False(t, got[0].CreatedAt.IsZero()) } -func TestCountPasswords(t *testing.T) { - json := `{ - "logins": [ - {"hostname": "https://a.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 1000}, - {"hostname": "https://b.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 2000}, - {"hostname": "https://c.com", "encryptedUsername": "", "encryptedPassword": "", "timeCreated": 3000} - ] - }` - path := createTestJSON(t, "logins.json", json) - - count, err := countPasswords(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountPasswords_Empty(t *testing.T) { - path := createTestJSON(t, "logins.json", `{"logins": []}`) - - count, err := countPasswords(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - func TestExtractPasswords_FormSubmitURLFallback(t *testing.T) { encB64 := loginPBEBase64(t) @@ -94,7 +77,9 @@ func TestExtractPasswords_FormSubmitURLFallback(t *testing.T) { path := createTestJSON(t, "logins.json", json) - got, err := extractPasswords(testGlobalSalt, path) + var out testCollector + err := extractPasswords(fixedKey(testGlobalSalt), path, &out) + got := collected[record.Login](t, &out) require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "https://fallback.com", got[0].URL) @@ -115,18 +100,23 @@ func TestExtractPasswords_DecryptFailureKeepsEntry(t *testing.T) { path := createTestJSON(t, "logins.json", json) - got, err := extractPasswords(testGlobalSalt, path) + var out testCollector + err := extractPasswords(fixedKey(testGlobalSalt), path, &out) + got := collected[record.Login](t, &out) require.NoError(t, err) require.Len(t, got, 1) assert.Equal(t, "https://bad.com", got[0].URL) assert.Empty(t, got[0].Username) // decrypt failed → empty assert.Empty(t, got[0].Password) // decrypt failed → empty + assert.Len(t, out.fails, 2) } func TestExtractPasswords_EmptyLogins(t *testing.T) { path := createTestJSON(t, "logins.json", `{"logins": []}`) - got, err := extractPasswords(testGlobalSalt, path) + var out testCollector + err := extractPasswords(fixedKey(testGlobalSalt), path, &out) + got := collected[record.Login](t, &out) require.NoError(t, err) assert.Empty(t, got) } diff --git a/browser/firefox/extract_storage.go b/internal/browser/firefox/extract_storage.go similarity index 74% rename from browser/firefox/extract_storage.go rename to internal/browser/firefox/extract_storage.go index 9c9527f..3dffc6f 100644 --- a/browser/firefox/extract_storage.go +++ b/internal/browser/firefox/extract_storage.go @@ -5,17 +5,15 @@ import ( "fmt" "strings" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/record" "github.com/moond4rk/hackbrowserdata/internal/sqlitex" ) -const ( - firefoxLocalStorageQuery = `SELECT originKey, key, value FROM webappsstore2` - firefoxCountLocalStorageQuery = `SELECT COUNT(*) FROM webappsstore2` -) +const firefoxLocalStorageQuery = `SELECT originKey, key, value FROM webappsstore2` -func extractLocalStorage(path string) ([]record.LocalStorage, error) { - return sqlitex.QueryRows(path, true, firefoxLocalStorageQuery, +func extractLocalStorage(path string, out browser.Collector) error { + entries, err := sqlitex.QueryRows(path, true, firefoxLocalStorageQuery, func(rows *sql.Rows) (record.LocalStorage, error) { var originKey, key, value string if err := rows.Scan(&originKey, &key, &value); err != nil { @@ -27,10 +25,11 @@ func extractLocalStorage(path string) ([]record.LocalStorage, error) { Value: value, }, nil }) -} - -func countLocalStorage(path string) (int, error) { - return sqlitex.CountRows(path, true, firefoxCountLocalStorageQuery) + if err != nil { + return err + } + emit(out, entries) + return nil } func reverseString(s string) string { diff --git a/browser/firefox/extract_storage_test.go b/internal/browser/firefox/extract_storage_test.go similarity index 79% rename from browser/firefox/extract_storage_test.go rename to internal/browser/firefox/extract_storage_test.go index da1717d..b7605e1 100644 --- a/browser/firefox/extract_storage_test.go +++ b/internal/browser/firefox/extract_storage_test.go @@ -5,6 +5,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/record" ) func setupWebappsDB(t *testing.T) string { @@ -19,7 +21,9 @@ func setupWebappsDB(t *testing.T) string { func TestExtractLocalStorage(t *testing.T) { path := setupWebappsDB(t) - got, err := extractLocalStorage(path) + var out testCollector + err := extractLocalStorage(path, &out) + got := collected[record.LocalStorage](t, &out) require.NoError(t, err) require.Len(t, got, 3) @@ -33,22 +37,6 @@ func TestExtractLocalStorage(t *testing.T) { assert.Equal(t, "abc123", byKey["http://example.com:8080/token"]) } -func TestCountLocalStorage(t *testing.T) { - path := setupWebappsDB(t) - - count, err := countLocalStorage(path) - require.NoError(t, err) - assert.Equal(t, 3, count) -} - -func TestCountLocalStorage_Empty(t *testing.T) { - path := createTestDB(t, "webappsstore.sqlite", []string{webappsstore2Schema}) - - count, err := countLocalStorage(path) - require.NoError(t, err) - assert.Equal(t, 0, count) -} - func TestParseOriginKey(t *testing.T) { tests := []struct { name string diff --git a/internal/browser/firefox/firefox.go b/internal/browser/firefox/firefox.go new file mode 100644 index 0000000..0785037 --- /dev/null +++ b/internal/browser/firefox/firefox.go @@ -0,0 +1,171 @@ +// Package firefox is the Firefox base: where Firefox keeps its profiles, how their files are parsed, and how each +// profile's own key4.db opens its logins. +package firefox + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +var ( + loginsJSON = browser.Source{Paths: []string{"logins.json"}} + keyStore = browser.Source{Paths: []string{"key4.db"}, Optional: true} + placesDB = browser.Source{Paths: []string{"places.sqlite"}} +) + +// Firefox keeps no credit cards or session storage that HBD reads, so those categories have no extractor. +var extractors = browser.Extractors{ + category.Password: {Sources: []browser.Source{loginsJSON, keyStore}, Extract: extractLogins}, + category.Cookie: plain(file("cookies.sqlite"), extractCookies), + category.Bookmark: plain(placesDB, extractBookmarks), + category.History: plain(placesDB, extractHistories), + category.Download: plain(placesDB, extractDownloads), + category.Extension: plain(file("extensions.json"), extractExtensions), + category.LocalStorage: plain(file("webappsstore.sqlite"), extractLocalStorage), +} + +// Discover finds def's Profiles directory and the profiles in it. -p names one profile, and its parent directory is +// searched, as today. +func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { + var errs []error + var dirs []browser.UserDataDir + for i, path := range userDataDirPaths(def, opts) { + dir := browser.UserDataDir{ID: dirID(def, i), Def: def, Path: path} + profiles, err := discoverProfiles(dir) + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + errs = append(errs, fmt.Errorf("%s: %w", path, err)) + continue + } + dir.Profiles = profiles + dirs = append(dirs, dir) + } + return dirs, errors.Join(errs...) +} + +func userDataDirPaths(def browser.Def, opts browser.DiscoverOptions) []string { + if opts.ProfilePath != "" { + return []string{filepath.Dir(filepath.Clean(opts.ProfilePath))} + } + paths := make([]string, 0, len(def.Platform().UserDataDirs)) + for _, rel := range def.Platform().UserDataDirs { + paths = append(paths, filepath.Join(opts.Home, filepath.FromSlash(rel))) + } + return paths +} + +func dirID(def browser.Def, i int) browser.DirID { + if i == 0 { + return browser.DirID(def.ID) + } + return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1)) +} + +// discoverProfiles takes every subdirectory holding a file some category reads, since profile directories have random +// names; key4.db alone does not make one. +func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { + entries, err := os.ReadDir(dir.Path) + if err != nil { + return nil, err + } + var profiles []browser.Profile + for _, e := range entries { + if e.IsDir() && hasDataFile(filepath.Join(dir.Path, e.Name())) { + profiles = append(profiles, browser.Profile{Name: e.Name(), Dir: e.Name()}) + } + } + return profiles, nil +} + +func hasDataFile(dir string) bool { + for _, e := range extractors { + for _, src := range e.Sources { + if src.Optional { + continue + } + for _, rel := range src.Paths { + if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(rel))); err == nil { + return true + } + } + } + } + return false +} + +// Extractors maps every category a Firefox profile supports to its extractor. +func Extractors(_ browser.UserDataDir, _ browser.Profile) browser.Extractors { + ex := make(browser.Extractors, len(extractors)) + for c, e := range extractors { + ex[c] = e + } + return ex +} + +func file(path string) browser.Source { return browser.Source{Paths: []string{path}} } + +func plain(src browser.Source, parse func(string, browser.Collector) error) browser.Extractor { + return browser.Extractor{ + Sources: []browser.Source{src}, + Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { + path, err := ps.Path(src) + if err != nil { + return err + } + return parse(path, out) + }, + } +} + +// extractLogins derives the profile's key only once a login needs it. Without a key the logins are still exported, +// their username and password empty, and the reason is the extraction's first problem. +func extractLogins(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { + path, err := ps.Path(loginsJSON) + if err != nil { + return err + } + var ( + key []byte + derived bool + ) + masterKey := func() []byte { + if !derived { + derived = true + k, keyErr := profileKey(ps, path) + if keyErr != nil { + out.Fail(fmt.Errorf("master key: %w", keyErr)) + } + key = k + } + return key + } + return extractPasswords(masterKey, path, out) +} + +func profileKey(ps browser.ProfileSnapshot, loginsPath string) ([]byte, error) { + key4Path, err := ps.Path(keyStore) + if err != nil { + return nil, err + } + return retrieveMasterKey(key4Path, loginsPath) +} + +// emit hands rows to out by pointer, because out stamps each record in place. +func emit[T any, P interface { + *T + record.Record +}](out browser.Collector, rows []T) { + for i := range rows { + out.Add(P(&rows[i])) + } +} diff --git a/internal/browser/firefox/firefox_test.go b/internal/browser/firefox/firefox_test.go new file mode 100644 index 0000000..ca51a7d --- /dev/null +++ b/internal/browser/firefox/firefox_test.go @@ -0,0 +1,165 @@ +package firefox + +import ( + "context" + "fmt" + "io/fs" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" +) + +func testDef(userDataDirs ...string) browser.Def { + p := browser.Platform{UserDataDirs: userDataDirs} + return browser.Def{ID: "firefox", Name: "Firefox", Base: browser.Firefox, Darwin: p, Linux: p, Windows: p} +} + +func touch(t *testing.T, parts ...string) { + t.Helper() + path := filepath.Join(parts...) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700)) + require.NoError(t, os.WriteFile(path, []byte("{}"), 0o600)) +} + +// snapshotOf lays fixture files out as one user data dir's snapshot, keyed by their path relative to the dir. +func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { + t.Helper() + root := t.TempDir() + for rel, src := range files { + dir := filepath.Join(root, "firefox", filepath.Dir(filepath.FromSlash(rel))) + require.NoError(t, os.MkdirAll(dir, 0o700)) + installFile(t, dir, src, filepath.Base(rel)) + } + return snapshot.Open(root).Snapshot("firefox") +} + +func TestDiscover_ProfilesAreDirsWithDataFiles(t *testing.T) { + home := t.TempDir() + touch(t, home, "Profiles", "abcd1234.default-release", "places.sqlite") + touch(t, home, "Profiles", "wxyz5678.work", "logins.json") + touch(t, home, "Profiles", "k3y0nly0.default", "key4.db") + touch(t, home, "Profiles", "Crash Reports", "InstallTime20240101000000") + touch(t, home, "Profiles", "profiles.ini") + + dirs, err := Discover(testDef("Profiles"), browser.DiscoverOptions{Home: home}) + require.NoError(t, err) + require.Len(t, dirs, 1) + assert.Equal(t, browser.DirID("firefox"), dirs[0].ID) + assert.Equal(t, filepath.Join(home, "Profiles"), dirs[0].Path) + assert.Equal(t, []browser.Profile{ + {Name: "abcd1234.default-release", Dir: "abcd1234.default-release"}, + {Name: "wxyz5678.work", Dir: "wxyz5678.work"}, + }, dirs[0].Profiles) +} + +func TestDiscover_MissingUserDataDirYieldsNothing(t *testing.T) { + dirs, err := Discover(testDef("Profiles"), browser.DiscoverOptions{Home: t.TempDir()}) + require.NoError(t, err) + assert.Empty(t, dirs) +} + +// A user data dir that exists but cannot be read must not look like a browser that is not installed. +func TestDiscover_UnreadableUserDataDirIsAnError(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("directory permissions do not deny reads here") + } + home := t.TempDir() + touch(t, home, "Profiles", "abcd1234.default-release", "places.sqlite") + profiles := filepath.Join(home, "Profiles") + require.NoError(t, os.Chmod(profiles, 0o000)) + defer func() { require.NoError(t, os.Chmod(profiles, 0o700)) }() + + dirs, err := Discover(testDef("Profiles"), browser.DiscoverOptions{Home: home}) + require.Error(t, err) + assert.Empty(t, dirs) +} + +// -p names one profile, yet every profile beside it is found too, as today; narrowing to it waits for the switch-over. +func TestDiscover_ProfilePathSearchesItsParent(t *testing.T) { + custom := t.TempDir() + touch(t, custom, "abcd1234.default-release", "places.sqlite") + touch(t, custom, "wxyz5678.work", "places.sqlite") + + opts := browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: filepath.Join(custom, "abcd1234.default-release")} + dirs, err := Discover(testDef("Profiles"), opts) + require.NoError(t, err) + require.Len(t, dirs, 1) + assert.Equal(t, custom, dirs[0].Path) + assert.Len(t, dirs[0].Profiles, 2) +} + +func TestExtractors_CoverFirefoxCategories(t *testing.T) { + ex := Extractors(browser.UserDataDir{Def: testDef()}, browser.Profile{}) + for _, c := range category.All() { + e, ok := ex[c] + if c == category.CreditCard || c == category.SessionStorage { + assert.Falsef(t, ok, "Firefox has no %s extractor", c) + continue + } + if assert.Truef(t, ok, "no extractor for %s", c) { + assert.NotNil(t, e.Extract, c) + assert.NotEmpty(t, e.Sources, c) + } + } +} + +// Without key4.db the logins are still exported with empty secrets, and the missing key is the first problem; before, +// decrypting a legacy-cipher login without a key panicked and ended the run. +func TestExtractLogins_WithoutKeyStore(t *testing.T) { + enc := loginPBEBase64(t) + logins := createTestJSON(t, "logins.json", fmt.Sprintf(`{"logins": [{"hostname": "https://a.test", + "encryptedUsername": %q, "encryptedPassword": %q, "timeCreated": 1700000000000}]}`, enc, enc)) + ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"p/logins.json": logins}), + browser.Profile{Name: "p", Dir: "p"}, nil) + + var out testCollector + require.NoError(t, extractLogins(context.Background(), ps, &out)) + got := collected[record.Login](t, &out) + require.Len(t, got, 1) + assert.Equal(t, "https://a.test", got[0].URL) + assert.Empty(t, got[0].Username) + assert.Empty(t, got[0].Password) + require.Len(t, out.fails, 3) + assert.ErrorIs(t, out.fails[0], fs.ErrNotExist) +} + +// A profile with no saved logins never needs its key, so an unreadable key4.db is no problem there. +func TestExtractLogins_NoLoginsNeverReadsTheKey(t *testing.T) { + ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ + "p/logins.json": createTestJSON(t, "logins.json", `{"logins": []}`), + "p/key4.db": createTestJSON(t, "key4.db", "not a database"), + }), browser.Profile{Name: "p", Dir: "p"}, nil) + + var out testCollector + require.NoError(t, extractLogins(context.Background(), ps, &out)) + assert.Empty(t, out.records) + assert.Empty(t, out.fails) +} + +// One snapshot serves every profile of a user data dir; each profile must read its own files from it. +func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) { + snap := snapshotOf(t, map[string]string{ + "a.default/places.sqlite": createTestDB(t, "places.sqlite", []string{mozPlacesSchema}, + insertMozPlace(1, "https://home.example", "Home", 1, 1700000000000000)), + "b.work/places.sqlite": createTestDB(t, "places.sqlite", []string{mozPlacesSchema}, + insertMozPlace(1, "https://work.example", "Work", 1, 1700000000000000)), + }) + dir := browser.UserDataDir{Def: testDef()} + want := map[string]string{"a.default": "Home", "b.work": "Work"} + for _, p := range []browser.Profile{{Name: "a.default", Dir: "a.default"}, {Name: "b.work", Dir: "b.work"}} { + var out testCollector + require.NoError(t, Extractors(dir, p)[category.History].Extract(context.Background(), browser.NewProfileSnapshot(snap, p, nil), &out)) + got := collected[record.History](t, &out) + require.Len(t, got, 1, p.Name) + assert.Equal(t, want[p.Name], got[0].Title, p.Name) + } +} diff --git a/browser/firefox/masterkey.go b/internal/browser/firefox/masterkey.go similarity index 91% rename from browser/firefox/masterkey.go rename to internal/browser/firefox/masterkey.go index 7726fdb..d8be134 100644 --- a/browser/firefox/masterkey.go +++ b/internal/browser/firefox/masterkey.go @@ -15,6 +15,28 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" ) +// retrieveMasterKey derives the key candidates in key4.db and returns the one that opens the logins in loginsPath. +func retrieveMasterKey(key4Path, loginsPath string) ([]byte, error) { + k4, err := readKey4DB(key4Path) + if err != nil { + return nil, err + } + + keys, err := k4.deriveKeys() + if err != nil { + return nil, err + } + if len(keys) == 0 { + return nil, errors.New("no valid master key candidates in key4.db") + } + + if key := validateKeyWithLogins(keys, loginsPath); key != nil { + return key, nil + } + + return nil, fmt.Errorf("derived %d key(s) but none could decrypt logins", len(keys)) +} + // key4DB holds the parsed contents of Firefox's key4.db NSS key storage. // // Firefox stores the master encryption key in key4.db using two SQLite tables: diff --git a/browser/firefox/masterkey_test.go b/internal/browser/firefox/masterkey_test.go similarity index 100% rename from browser/firefox/masterkey_test.go rename to internal/browser/firefox/masterkey_test.go diff --git a/internal/browser/firefox/testutil_test.go b/internal/browser/firefox/testutil_test.go new file mode 100644 index 0000000..6deb431 --- /dev/null +++ b/internal/browser/firefox/testutil_test.go @@ -0,0 +1,197 @@ +package firefox + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + _ "modernc.org/sqlite" + + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +// --------------------------------------------------------------------------- +// Real Firefox table schemas — extracted via `sqlite3 ".schema "`. +// --------------------------------------------------------------------------- + +const mozCookiesSchema = `CREATE TABLE moz_cookies ( + id INTEGER PRIMARY KEY, + originAttributes TEXT NOT NULL DEFAULT '', + name TEXT, + value TEXT, + host TEXT, + path TEXT, + expiry INTEGER, + lastAccessed INTEGER, + creationTime INTEGER, + isSecure INTEGER, + isHttpOnly INTEGER, + inBrowserElement INTEGER DEFAULT 0, + sameSite INTEGER DEFAULT 0, + rawSameSite INTEGER DEFAULT 0, + schemeMap INTEGER DEFAULT 0, + isPartitionedAttributeSet INTEGER DEFAULT 0, + CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes) +)` + +const mozPlacesSchema = `CREATE TABLE moz_places ( + id INTEGER PRIMARY KEY, + url LONGVARCHAR, + title LONGVARCHAR, + rev_host LONGVARCHAR, + visit_count INTEGER DEFAULT 0, + hidden INTEGER DEFAULT 0 NOT NULL, + typed INTEGER DEFAULT 0 NOT NULL, + frecency INTEGER DEFAULT -1 NOT NULL, + last_visit_date INTEGER, + guid TEXT, + foreign_count INTEGER DEFAULT 0 NOT NULL, + url_hash INTEGER DEFAULT 0 NOT NULL, + description TEXT, + preview_image_url TEXT, + site_name TEXT, + origin_id INTEGER, + recalc_frecency INTEGER NOT NULL DEFAULT 0, + alt_frecency INTEGER, + recalc_alt_frecency INTEGER NOT NULL DEFAULT 0 +)` + +const mozBookmarksSchema = `CREATE TABLE moz_bookmarks ( + id INTEGER PRIMARY KEY, + type INTEGER, + fk INTEGER DEFAULT NULL, + parent INTEGER, + position INTEGER, + title LONGVARCHAR, + keyword_id INTEGER, + folder_type TEXT, + dateAdded INTEGER, + lastModified INTEGER, + guid TEXT, + syncStatus INTEGER NOT NULL DEFAULT 0, + syncChangeCounter INTEGER NOT NULL DEFAULT 1 +)` + +const mozAnnosSchema = `CREATE TABLE moz_annos ( + id INTEGER PRIMARY KEY, + place_id INTEGER NOT NULL, + anno_attribute_id INTEGER, + content LONGVARCHAR, + flags INTEGER DEFAULT 0, + expiration INTEGER DEFAULT 0, + type INTEGER DEFAULT 0, + dateAdded INTEGER DEFAULT 0, + lastModified INTEGER DEFAULT 0 +)` + +const webappsstore2Schema = `CREATE TABLE webappsstore2 ( + originAttributes TEXT, + originKey TEXT, + scope TEXT, + key TEXT, + value TEXT +)` + +// --------------------------------------------------------------------------- +// INSERT helpers +// --------------------------------------------------------------------------- + +func insertMozCookie(name, value, host, path string, creationTime, expiry int64, isSecure, isHTTPOnly int) string { + return fmt.Sprintf( + `INSERT INTO moz_cookies (name, value, host, path, creationTime, expiry, isSecure, isHttpOnly, lastAccessed) + VALUES ('%s', '%s', '%s', '%s', %d, %d, %d, %d, %d)`, + name, value, host, path, creationTime, expiry, isSecure, isHTTPOnly, creationTime, + ) +} + +func insertMozPlace(id int, url, title string, visitCount int, lastVisitDate int64) string { + return fmt.Sprintf( + `INSERT INTO moz_places (id, url, title, visit_count, last_visit_date, rev_host, guid, url_hash) + VALUES (%d, '%s', '%s', %d, %d, '', 'guid-%d', 0)`, + id, url, title, visitCount, lastVisitDate, id, + ) +} + +func insertMozBookmark(id, fk, bookmarkType int, title string, dateAdded int64) string { + return fmt.Sprintf( + `INSERT INTO moz_bookmarks (id, type, fk, parent, position, title, dateAdded, lastModified, guid) + VALUES (%d, %d, %d, 0, 0, '%s', %d, %d, 'bm-guid-%d')`, + id, bookmarkType, fk, title, dateAdded, dateAdded, id, + ) +} + +func insertMozAnno(placeID int, content string, dateAdded int64) string { + return fmt.Sprintf( + `INSERT INTO moz_annos (place_id, anno_attribute_id, content, dateAdded, lastModified) + VALUES (%d, 1, '%s', %d, %d)`, + placeID, content, dateAdded, dateAdded, + ) +} + +func insertWebappsstore(originKey, key, value string) string { + return fmt.Sprintf( + `INSERT INTO webappsstore2 (originAttributes, originKey, scope, key, value) + VALUES ('', '%s', '', '%s', '%s')`, + originKey, key, value, + ) +} + +// --------------------------------------------------------------------------- +// Test fixture builders +// --------------------------------------------------------------------------- + +// installFile copies a test fixture file into a profile directory. +func installFile(t *testing.T, profileDir, srcPath, dstName string) { + t.Helper() + data, err := os.ReadFile(srcPath) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(profileDir, dstName), data, 0o644)) +} + +func createTestDB(t *testing.T, name string, schemas []string, inserts ...string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + db, err := sql.Open("sqlite", path) + require.NoError(t, err) + defer db.Close() + + for _, schema := range schemas { + _, err = db.Exec(schema) + require.NoError(t, err) + } + for _, stmt := range inserts { + _, err = db.Exec(stmt) + require.NoError(t, err) + } + return path +} + +func createTestJSON(t *testing.T, name, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + return path +} + +// testCollector keeps what an extractor hands it, in order. +type testCollector struct { + records []record.Record + fails []error +} + +func (c *testCollector) Add(r record.Record) { c.records = append(c.records, r) } +func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } + +func collected[T any](t *testing.T, c *testCollector) []T { + t.Helper() + got := make([]T, 0, len(c.records)) + for _, r := range c.records { + v, ok := any(r).(*T) + require.Truef(t, ok, "collected a %T, want *%T", r, *new(T)) + got = append(got, *v) + } + return got +} diff --git a/internal/crypto/asn1pbe.go b/internal/crypto/asn1pbe.go index 4dbd55c..51fc4de 100644 --- a/internal/crypto/asn1pbe.go +++ b/internal/crypto/asn1pbe.go @@ -188,6 +188,9 @@ func (l credentialPBE) Decrypt(masterKey []byte) ([]byte, error) { // The cipher is inferred from IV length (avoids fragile OID checks): switch len(iv) { case des.BlockSize: // 8: 3DES-CBC (legacy Firefox) + if len(key) < des3KeySize { + return nil, errShortKey + } return DES3Decrypt(key[:des3KeySize], iv, l.Encrypted) case aes.BlockSize: // 16: AES-256-CBC (Firefox 144+) return AESCBCDecrypt(key, iv, l.Encrypted) @@ -200,6 +203,9 @@ func (l credentialPBE) Encrypt(masterKey, plaintext []byte) ([]byte, error) { key, iv := l.deriveKeyAndIV(masterKey) switch len(iv) { case des.BlockSize: + if len(key) < des3KeySize { + return nil, errShortKey + } return DES3Encrypt(key[:des3KeySize], iv, plaintext) case aes.BlockSize: return AESCBCEncrypt(key, iv, plaintext) diff --git a/internal/crypto/asn1pbe_test.go b/internal/crypto/asn1pbe_test.go index 31dbe91..eabf3b5 100644 --- a/internal/crypto/asn1pbe_test.go +++ b/internal/crypto/asn1pbe_test.go @@ -350,3 +350,17 @@ func TestCredentialPBE_UnsupportedIVLength(t *testing.T) { _, err = pbe.Encrypt([]byte("key"), []byte("data")) require.ErrorIs(t, err, errUnsupportedIVLen) } + +// A profile whose key could not be derived passes a nil key, which must fail instead of panicking. +func TestCredentialPBE_ShortKey(t *testing.T) { + raw, err := hex.DecodeString(credentialPBETestCases[0].RawHexPBE) + require.NoError(t, err) + pbe, err := NewASN1PBE(raw) + require.NoError(t, err) + for _, key := range [][]byte{nil, make([]byte, des3KeySize-1)} { + _, err := pbe.Decrypt(key) + require.ErrorIs(t, err, errShortKey) + _, err = pbe.Encrypt(key, pbePlaintext) + require.ErrorIs(t, err, errShortKey) + } +} diff --git a/internal/crypto/errors.go b/internal/crypto/errors.go index 9bf7985..50bdbc0 100644 --- a/internal/crypto/errors.go +++ b/internal/crypto/errors.go @@ -10,5 +10,6 @@ var ( errInvalidPadding = errors.New("invalid PKCS5 padding") errInvalidNonceLen = errors.New("nonce length must equal GCM nonce size") errUnsupportedIVLen = errors.New("unsupported IV length") + errShortKey = errors.New("key is shorter than the cipher needs") errDecodeASN1 = errors.New("failed to decode ASN1 data") ) diff --git a/rfcs/000-goals-and-constraints.md b/rfcs/000-goals-and-constraints.md index f52d391..35493dd 100644 --- a/rfcs/000-goals-and-constraints.md +++ b/rfcs/000-goals-and-constraints.md @@ -43,7 +43,7 @@ The rewrite is invisible from the outside. Every item below behaves exactly as i | Archive | zip layout `/`, readable by v1.1.0 `restore` | | Exit status | `0` when the run completes (including partial results and "no browsers found"); `1` when it cannot start or finish | -Not part of the contract: log lines and the human-readable summary on stderr, and row order where today's order is unspecified or wrong. Output may change only for listed bug fixes where today's output is wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, the `browser` value `restore` stamps, and CocCoc cookies on a Windows machine that also has Yandex ([RFC-008](008-output-and-export.md)); each is called out where it is fixed. +Not part of the contract: log lines and the human-readable summary on stderr, and row order where today's order is unspecified or wrong. Output may change only for listed bug fixes where today's output is wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, Firefox logins from a profile whose key cannot be recovered, the `browser` value `restore` stamps, and CocCoc cookies on a Windows machine that also has Yandex ([RFC-008](008-output-and-export.md)); each is called out where it is fixed. ## Hard constraints diff --git a/rfcs/008-output-and-export.md b/rfcs/008-output-and-export.md index 0f2dba1..18af4df 100644 --- a/rfcs/008-output-and-export.md +++ b/rfcs/008-output-and-export.md @@ -71,6 +71,7 @@ Extractors emit records one at a time ([RFC-003](003-core-types.md)), but sortin - **Firefox history order** — `visit_count` descending, like Chromium and Safari. - **Firefox bookmarks** — `folder` holds the real folder name instead of `url`, and `type` and `id` are filled; today they are always `url`, empty, and `0`. - **Safari bookmark IDs** — unique across the whole bookmark tree; today each ID is the index among its siblings, so IDs repeat across folders. +- **Firefox logins without a key** — when a profile's key cannot be recovered (no `key4.db`, or a primary password is set), its logins are exported with empty usernames and passwords and the extraction is `partial`; today the run panics as soon as one of those logins uses the legacy cipher. - **`browser` in `restore` output** — the display name (`Chrome`), as `dump` writes it; today `restore` writes the vault key (`chrome`). - **CocCoc cookies beside Yandex** — on Windows, ABE looks for a browser's program in its own install locations before registry App Paths. CocCoc and Yandex both ship `browser.exe`, and App Paths names only one of them, so today CocCoc's key is requested from Yandex's program and its `v20` cookies export with empty values. diff --git a/rfcs/011-testing-and-quality.md b/rfcs/011-testing-and-quality.md index 9da416d..593f1ea 100644 --- a/rfcs/011-testing-and-quality.md +++ b/rfcs/011-testing-and-quality.md @@ -40,6 +40,7 @@ Each bug designed out by this rewrite gets a test that would have caught it, so - **Firefox bookmark fields** (`folder` always `url`, `type` empty, `id` 0): golden assertions on a fixture with nested folders. - **Firefox history order**: `visit_count` descending for every browser, Firefox included. - **Safari bookmark IDs**: unique across the whole tree, not repeated per folder. +- **Firefox without a key**: a profile with no `key4.db` still exports its logins with empty secrets, the extraction is `partial`, and the run goes on; a missing key makes decryption fail instead of panicking. - **Arc multi-dir**: two `arc` user data dirs yield IDs `arc` and `arc-2`, distinct snapshots, and distinct `keys.json` vaults, while overrides and the vaults' `browser` key still use `arc`. - **`--zip` data loss**: a failing zip write leaves every output file in place. - **Late flag validation**: `-f bogus` exits `1` with no discovery call and no password resolution (both injected as spies). diff --git a/rfcs/012-migration-roadmap.md b/rfcs/012-migration-roadmap.md index b9b553c..a9fa607 100644 --- a/rfcs/012-migration-roadmap.md +++ b/rfcs/012-migration-roadmap.md @@ -54,6 +54,7 @@ Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layou - Port the Firefox and Safari bases one category at a time, each with a `testdata/` fixture and golden. - Land the remaining listed output fixes here — Firefox bookmark fields and Safari bookmark IDs — each with its regression test and as an expected diff in the parity suite. +- With the Firefox base, a profile whose key cannot be recovered exports its logins instead of stopping the run ([RFC-008](008-output-and-export.md)); the goldens do not change. ### Phase 7 — Switch over