Files
HackBrowserData/browser/firefox/firefox.go
T
Roger 1a3aea553e feat: add Firefox Browser with new v2 architecture (#536)
* feat: add Firefox Browser implementation with new v2 architecture

Add Firefox NewBrowsers + Extract pipeline following the Chromium v2
pattern. Firefox-specific differences handled:
- Profile discovery: random directory names (e.g. abc123.default-release)
- Master key: NSS/ASN1PBE from key4.db (platform-agnostic, no DPAPI/Keychain)
- Key validation: reuse logins.json from acquireFiles tempPaths
- Extract: only Password needs masterKey; Cookie is plaintext
- No CreditCard or SessionStorage support

Files:
- firefox_new.go: Browser struct, NewBrowsers, Extract, getMasterKey,
  extractCategory, deriveKeys, validateKeyWithLogins, profile discovery
- masterkey.go: extracted shared NSS logic (processMasterKey, queryMetaData,
  queryNssPrivateCandidates, parseLoginCipherPairs, canDecryptAnyLoginCipherPair)
- firefox_new_test.go: table-driven tests with shared fixtures
- source.go: remove dataSource wrapper, use []sourcePath directly
- firefox.go: remove functions moved to masterkey.go

* fix: address Copilot review feedback on Firefox v2

- Fix stale comment referencing removed readLoginCipherPairs
- Rename finallyKey to derivedKey for clarity in processMasterKey
- Add sqlite driver import to masterkey.go for self-containedness

* refactor: rewrite Firefox masterkey and improve naming

Masterkey rewrite:
- Replace raw SQL functions with structured key4DB type (globalSalt,
  passwordCheck, privateKeys) for clear data modeling
- Split processMasterKey into verifyPasswordCheck + decryptPrivateKey
- Add nssKeyTypeTag constant for the magic bytes
- Rename finallyKey to derivedKey
- Add sqlite driver import for self-containedness
- Return error (not fallback) when logins validation explicitly fails

Naming cleanup:
- loginPair → encryptedLogin (clarify these are encrypted blobs)
- parseLoginPairs → sampleEncryptedLogins (clarify sampling purpose)
- canDecryptLogin → tryDecryptLogins (accurate verb, plural alignment)
- Expand abbreviated variables: p→login, uPBE→userPBE, pPBE→pwdPBE

Password extraction:
- Keep entries when decryptPBE fails (URL preserved, user/pwd empty)
- Align with Chromium behavior where decrypt failure doesn't skip records

Old code cleanup:
- firefox.go GetMasterKey now delegates to retrieveMasterKey
- Remove functions moved to masterkey.go

* docs: add RFC-003 for crypto package naming cleanup

Track accumulated naming and structural issues in crypto/asn1pbe.go
and cross-browser shared code for a future dedicated refactoring pass.

* refactor: move masterkey tests to masterkey_test.go

- Rename firefox_test.go to masterkey_test.go since all tests in
  this file test masterkey.go functions (readKey4DB, sampleEncryptedLogins)
- Fix TestReadKey4DB to check nssPrivate rows as a set instead of
  assuming SQLite insertion order
- Future deletion of firefox.go won't accidentally remove masterkey tests
2026-04-04 01:41:02 +08:00

118 lines
2.9 KiB
Go

package firefox
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
_ "modernc.org/sqlite" // sqlite3 driver TODO: replace with chooseable driver
"github.com/moond4rk/hackbrowserdata/browserdata"
"github.com/moond4rk/hackbrowserdata/log"
"github.com/moond4rk/hackbrowserdata/types"
"github.com/moond4rk/hackbrowserdata/utils/fileutil"
"github.com/moond4rk/hackbrowserdata/utils/typeutil"
)
type Firefox struct {
name string
storage string
profilePath string
masterKey []byte
items []types.DataType
itemPaths map[types.DataType]string
}
var ErrProfilePathNotFound = errors.New("profile path not found")
// New returns new Firefox instances.
func New(profilePath string, items []types.DataType) ([]*Firefox, error) {
multiItemPaths := make(map[string]map[types.DataType]string)
// ignore walk dir error since it can be produced by a single entry
_ = filepath.WalkDir(profilePath, firefoxWalkFunc(items, multiItemPaths))
firefoxList := make([]*Firefox, 0, len(multiItemPaths))
for name, itemPaths := range multiItemPaths {
firefoxList = append(firefoxList, &Firefox{
name: fmt.Sprintf("firefox-%s", name),
items: typeutil.Keys(itemPaths),
itemPaths: itemPaths,
})
}
return firefoxList, nil
}
func (f *Firefox) copyItemToLocal() error {
for i, path := range f.itemPaths {
filename := i.TempFilename()
if err := fileutil.CopyFile(path, filename); err != nil {
return err
}
}
return nil
}
func firefoxWalkFunc(items []types.DataType, multiItemPaths map[string]map[types.DataType]string) fs.WalkDirFunc {
return func(path string, info fs.DirEntry, err error) error {
if err != nil {
if os.IsPermission(err) {
log.Warnf("skipping walk firefox path %s permission error: %v", path, err)
return nil
}
return err
}
for _, v := range items {
if info.Name() == v.Filename() {
parentBaseDir := fileutil.ParentBaseDir(path)
if _, exist := multiItemPaths[parentBaseDir]; exist {
multiItemPaths[parentBaseDir][v] = path
} else {
multiItemPaths[parentBaseDir] = map[types.DataType]string{v: path}
}
}
}
return nil
}
}
// GetMasterKey returns master key of Firefox. from key4.db
func (f *Firefox) GetMasterKey() ([]byte, error) {
tempFilename := types.FirefoxKey4.TempFilename()
defer os.Remove(tempFilename)
loginsPath := types.FirefoxPassword.TempFilename()
return retrieveMasterKey(tempFilename, loginsPath)
}
func (f *Firefox) Name() string {
return f.name
}
func (f *Firefox) BrowsingData(isFullExport bool) (*browserdata.BrowserData, error) {
dataTypes := f.items
if !isFullExport {
dataTypes = types.FilterSensitiveItems(f.items)
}
data := browserdata.New(dataTypes)
if err := f.copyItemToLocal(); err != nil {
return nil, err
}
masterKey, err := f.GetMasterKey()
if err != nil {
return nil, err
}
f.masterKey = masterKey
if err := data.Recovery(f.masterKey); err != nil {
return nil, err
}
return data, nil
}