mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
test(cmd): add Firefox and Safari extract goldens (#658)
Phase 6 moves the Firefox and Safari parsers, so today's output is locked first, as the Chromium goldens were before Phase 5.
This commit is contained in:
1 parent
9d51aa869e
commit
bc59bd57bb
13 files changed
+2206
-67
No files matched your search
@@ -2,11 +2,9 @@ package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -16,7 +14,6 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/browser/chromium"
|
||||
@@ -76,7 +73,7 @@ func chromiumFixtureBrowsers(t *testing.T, root string) []browser.Browser {
|
||||
|
||||
func chromiumFixtureUserData(t *testing.T, userDataDir, browserKey string) {
|
||||
t.Helper()
|
||||
chromiumFixtureWrite(t, filepath.Join(userDataDir, "Local State"), "{}")
|
||||
fixtureWrite(t, filepath.Join(userDataDir, "Local State"), "{}")
|
||||
for _, p := range chromiumFixtureProfiles {
|
||||
site := p.label + "." + browserKey + ".test"
|
||||
chromiumFixtureProfile(t, filepath.Join(userDataDir, p.dir), site, p.start, p.accountLogins)
|
||||
@@ -100,21 +97,21 @@ func chromiumFixtureProfile(t *testing.T, dir, site string, start time.Time, acc
|
||||
}
|
||||
day := 24 * time.Hour
|
||||
|
||||
chromiumFixtureWrite(t, filepath.Join(dir, "Preferences"), "{}")
|
||||
fixtureWrite(t, filepath.Join(dir, "Preferences"), "{}")
|
||||
|
||||
chromiumFixtureSQLite(t, filepath.Join(dir, "Login Data"), chromiumFixtureLoginsSchema,
|
||||
fixtureSQLite(t, filepath.Join(dir, "Login Data"), chromiumFixtureLoginsSchema,
|
||||
chromiumFixtureInsertLogin(link("accounts", "/"), link("accounts", "/login"), "alice",
|
||||
v10("correct-horse-battery-staple"), at(time.Hour)),
|
||||
chromiumFixtureInsertLogin(link("shop", "/"), link("shop", "/signin"), "alice@"+site, v10(`pa,ss"word`), at(2*time.Hour)),
|
||||
)
|
||||
if accountLogins {
|
||||
chromiumFixtureSQLite(t, filepath.Join(dir, "Login Data For Account"), chromiumFixtureLoginsSchema,
|
||||
fixtureSQLite(t, filepath.Join(dir, "Login Data For Account"), chromiumFixtureLoginsSchema,
|
||||
chromiumFixtureInsertLogin(link("sync", "/"), link("sync", "/auth"), "alice", v10("synced-secret"), at(90*time.Minute)),
|
||||
)
|
||||
}
|
||||
|
||||
domain, www, app := "."+site, "www."+site, "app."+site
|
||||
chromiumFixtureSQLite(t, filepath.Join(dir, "Network", "Cookies"), chromiumFixtureCookiesSchema,
|
||||
fixtureSQLite(t, filepath.Join(dir, "Network", "Cookies"), chromiumFixtureCookiesSchema,
|
||||
chromiumFixtureInsertCookie("SID", domain, "/", v20(hostBound(domain, "sid-"+site)),
|
||||
at(10*time.Minute+123456*time.Microsecond), at(365*day), 1, 1, 1),
|
||||
chromiumFixtureInsertCookie("prefs", www, "/settings", v10("theme=dark"), at(20*time.Minute), at(30*day), 0, 0, 2),
|
||||
@@ -122,7 +119,7 @@ func chromiumFixtureProfile(t *testing.T, dir, site string, start time.Time, acc
|
||||
chromiumFixtureInsertCookie("session", app, "/", v20("ephemeral"), at(40*time.Minute), 0, 1, 1, -1),
|
||||
)
|
||||
|
||||
chromiumFixtureSQLite(t, filepath.Join(dir, "History"), chromiumFixtureURLsSchema, chromiumFixtureDownloadsSchema,
|
||||
fixtureSQLite(t, filepath.Join(dir, "History"), chromiumFixtureURLsSchema, chromiumFixtureDownloadsSchema,
|
||||
chromiumFixtureInsertURL(link("www", "/"), "Home", 42, at(3*time.Hour)),
|
||||
chromiumFixtureInsertURL(link("docs", "/guide?q=go&lang=en"), `Guide, "quoted" & <b>bold</b>`, 7, at(4*time.Hour)),
|
||||
chromiumFixtureInsertURL(link("news", "/ja"), "ニュース", 3, at(5*time.Hour)),
|
||||
@@ -132,15 +129,15 @@ func chromiumFixtureProfile(t *testing.T, dir, site string, start time.Time, acc
|
||||
1048576, at(7*time.Hour), 0),
|
||||
)
|
||||
|
||||
chromiumFixtureWrite(t, filepath.Join(dir, "Bookmarks"),
|
||||
fixtureWrite(t, filepath.Join(dir, "Bookmarks"),
|
||||
fmt.Sprintf(chromiumFixtureBookmarks, site, at(0), at(8*time.Hour), at(9*time.Hour), at(10*time.Hour)))
|
||||
|
||||
chromiumFixtureSQLite(t, filepath.Join(dir, "Web Data"), chromiumFixtureCreditCardsSchema,
|
||||
fixtureSQLite(t, filepath.Join(dir, "Web Data"), chromiumFixtureCreditCardsSchema,
|
||||
chromiumFixtureInsertCreditCard("Alice Example", 4, 2031, v10("4111111111111111"), "Travel", "billing-home"),
|
||||
chromiumFixtureInsertCreditCard("Bob Example", 11, 2029, v10("5500005555555559"), "", ""),
|
||||
)
|
||||
|
||||
chromiumFixtureWrite(t, filepath.Join(dir, "Secure Preferences"), chromiumFixtureSecurePreferences)
|
||||
fixtureWrite(t, filepath.Join(dir, "Secure Preferences"), chromiumFixtureSecurePreferences)
|
||||
|
||||
origin := link("app", "")
|
||||
dataKey := "_" + origin + "\x00"
|
||||
@@ -191,24 +188,6 @@ func chromiumFixtureUTF16Raw(s string) string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func chromiumFixtureWrite(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
|
||||
}
|
||||
|
||||
func chromiumFixtureSQLite(t *testing.T, path string, stmts ...string) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
|
||||
db, err := sql.Open("sqlite", path)
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
for _, stmt := range stmts {
|
||||
_, err = db.Exec(stmt)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
func chromiumFixtureLevelDB(t *testing.T, dir string, entries map[string]string) {
|
||||
t.Helper()
|
||||
keys := make([]string, 0, len(entries))
|
||||
|
||||
@@ -1,43 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
)
|
||||
|
||||
func TestExtractGolden(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
chromiumFixtureInstallations(t, root)
|
||||
assertExtractGoldens(t, "extract", func(t *testing.T, format string) string {
|
||||
return extractGoldenRun(t, chromiumFixtureBrowsers(t, root), format)
|
||||
})
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
format string
|
||||
golden string
|
||||
jsonFallback bool
|
||||
}{
|
||||
{format: "csv", golden: "extract-csv.golden"},
|
||||
{format: "json", golden: "extract-json.golden"},
|
||||
{format: "cookie-editor", golden: "extract-cookie-editor.golden", jsonFallback: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
func TestExtractGoldenFirefox(t *testing.T) {
|
||||
profilesDir := filepath.Join(t.TempDir(), "firefox")
|
||||
firefoxFixtureUserData(t, profilesDir)
|
||||
assertExtractGoldens(t, "extract-firefox", func(t *testing.T, format string) string {
|
||||
return extractGoldenRun(t, firefoxFixtureBrowsers(t, profilesDir), format)
|
||||
})
|
||||
}
|
||||
|
||||
func TestExtractGoldenSafari(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
// Safari reads passwords from the login keychain under the home directory, which must not be the real one.
|
||||
t.Setenv("HOME", home)
|
||||
safariFixtureLibrary(t, filepath.Join(home, "Library"))
|
||||
assertExtractGoldens(t, "extract-safari", func(t *testing.T, format string) string {
|
||||
return extractGoldenRun(t, safariFixtureBrowsers(t, home), format)
|
||||
})
|
||||
}
|
||||
|
||||
var extractGoldenFormats = []struct {
|
||||
format string
|
||||
jsonFallback bool
|
||||
}{
|
||||
{format: "csv"},
|
||||
{format: "json"},
|
||||
{format: "cookie-editor", jsonFallback: true},
|
||||
}
|
||||
|
||||
func assertExtractGoldens(t *testing.T, prefix string, run func(t *testing.T, format string) string) {
|
||||
t.Helper()
|
||||
for _, tt := range extractGoldenFormats {
|
||||
tt := tt
|
||||
t.Run(tt.format, func(t *testing.T) {
|
||||
out := extractGoldenRun(t, root, tt.format)
|
||||
out := run(t, tt.format)
|
||||
got := bundleDir(t, out)
|
||||
if tt.jsonFallback {
|
||||
assertJSONFallback(t, out, extractGoldenRun(t, root, "json"))
|
||||
assertJSONFallback(t, out, run(t, "json"))
|
||||
got = bundleFiles(t, out, "cookie.json")
|
||||
}
|
||||
assertGolden(t, tt.golden, got)
|
||||
assertGolden(t, prefix+"-"+tt.format+".golden", got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func extractGoldenRun(t *testing.T, root, format string) string {
|
||||
func extractGoldenRun(t *testing.T, browsers []browser.Browser, format string) string {
|
||||
t.Helper()
|
||||
out := t.TempDir()
|
||||
require.NoError(t, extractAndWrite(chromiumFixtureBrowsers(t, root), category.All(), out, format, false))
|
||||
require.NoError(t, extractAndWrite(browsers, category.All(), out, format, false))
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/asn1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/browser/firefox"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/crypto"
|
||||
"github.com/moond4rk/hackbrowserdata/types"
|
||||
)
|
||||
|
||||
// home's logins open only with its second key candidate (AES-256) and work's with its only one (3DES), so the golden
|
||||
// covers the candidate check and both login ciphers.
|
||||
var firefoxFixtureProfiles = []struct {
|
||||
dir string
|
||||
label string
|
||||
start time.Time
|
||||
globalSalt []byte
|
||||
keys [][]byte
|
||||
}{
|
||||
{
|
||||
dir: "abcd1234.default-release", label: "home", start: time.Date(2024, 3, 1, 9, 0, 0, 0, time.UTC),
|
||||
globalSalt: []byte("home-global-salt-20b"),
|
||||
keys: [][]byte{[]byte("home-3des-key-0123456789"), []byte("home-aes256-key-0123456789abcdef")},
|
||||
},
|
||||
{
|
||||
dir: "wxyz5678.work", label: "work", start: time.Date(2024, 6, 1, 9, 0, 0, 0, time.UTC),
|
||||
globalSalt: []byte("work-global-salt-20b"),
|
||||
keys: [][]byte{[]byte("work-3des-key-0123456789")},
|
||||
},
|
||||
}
|
||||
|
||||
var firefoxFixtureKeyID = []byte{0xf8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
|
||||
|
||||
var (
|
||||
oidPBES2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 13}
|
||||
oidPBKDF2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 12}
|
||||
oidHMACWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 9}
|
||||
oidAES256CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 42}
|
||||
oidDESEDE3CBC = asn1.ObjectIdentifier{1, 2, 840, 113549, 3, 7}
|
||||
)
|
||||
|
||||
func firefoxFixtureBrowsers(t *testing.T, profilesDir string) []browser.Browser {
|
||||
t.Helper()
|
||||
b, err := firefox.NewBrowser(types.BrowserConfig{
|
||||
Key: "firefox",
|
||||
Name: "Firefox",
|
||||
Kind: types.Firefox,
|
||||
UserDataDir: profilesDir,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, b)
|
||||
return []browser.Browser{b}
|
||||
}
|
||||
|
||||
func firefoxFixtureUserData(t *testing.T, profilesDir string) {
|
||||
t.Helper()
|
||||
fixtureWrite(t, filepath.Join(profilesDir, "profiles.ini"), "[General]\nStartWithLastProfile=1\n")
|
||||
fixtureWrite(t, filepath.Join(profilesDir, "Crash Reports", "InstallTime20240101000000"), "1704067200")
|
||||
for _, p := range firefoxFixtureProfiles {
|
||||
firefoxFixtureProfile(t, filepath.Join(profilesDir, p.dir), p.label+".firefox.test", p.start, p.globalSalt, p.keys)
|
||||
}
|
||||
}
|
||||
|
||||
func firefoxFixtureProfile(t *testing.T, dir, site string, start time.Time, globalSalt []byte, keys [][]byte) {
|
||||
t.Helper()
|
||||
micros := func(offset time.Duration) int64 { return start.Add(offset).UnixMicro() }
|
||||
millis := func(offset time.Duration) int64 { return start.Add(offset).UnixMilli() }
|
||||
seconds := func(offset time.Duration) int64 { return start.Add(offset).Unix() }
|
||||
link := func(host, path string) string { return "https://" + host + "." + site + path }
|
||||
day := 24 * time.Hour
|
||||
|
||||
key4 := []string{
|
||||
firefoxFixtureMetaDataSchema,
|
||||
firefoxFixtureNSSPrivateSchema,
|
||||
fmt.Sprintf(`INSERT INTO metaData (id, item1, item2) VALUES ('password', x'%x', x'%x')`,
|
||||
globalSalt, firefoxFixturePBES2Seal(t, globalSalt, site+"/password-check", []byte("password-check"))),
|
||||
}
|
||||
for i, key := range keys {
|
||||
key4 = append(key4, fmt.Sprintf(`INSERT INTO nssPrivate (id, a11, a102) VALUES (%d, x'%x', x'%x')`,
|
||||
i+1, firefoxFixturePBES2Seal(t, globalSalt, fmt.Sprintf("%s/key-%d", site, i), key), firefoxFixtureKeyID))
|
||||
}
|
||||
fixtureSQLite(t, filepath.Join(dir, "key4.db"), key4...)
|
||||
|
||||
loginKey := keys[len(keys)-1]
|
||||
seal := func(field, plaintext string) string {
|
||||
return firefoxFixtureLoginSeal(t, loginKey, site+"/"+field, plaintext)
|
||||
}
|
||||
fixtureWrite(t, filepath.Join(dir, "logins.json"), fmt.Sprintf(firefoxFixtureLogins, site,
|
||||
seal("1/username", "alice"), seal("1/password", "correct-horse-battery-staple"), millis(time.Hour+250*time.Millisecond),
|
||||
seal("2/username", "alice@"+site), seal("2/password", `pa,ss"word`), millis(2*time.Hour),
|
||||
seal("3/username", "alice"), seal("3/password", "pässwörd"), millis(90*time.Minute),
|
||||
))
|
||||
|
||||
domain := "." + site
|
||||
fixtureSQLite(t, filepath.Join(dir, "cookies.sqlite"), firefoxFixtureCookiesSchema,
|
||||
firefoxFixtureInsertCookie("SID", "sid-"+site, domain, "/", seconds(365*day), micros(10*time.Minute+123456*time.Microsecond), 1, 1, 1),
|
||||
firefoxFixtureInsertCookie("prefs", "theme=dark", "www."+site, "/settings", seconds(30*day), micros(20*time.Minute), 0, 0, 2),
|
||||
firefoxFixtureInsertCookie("tracker", "opt-out", domain, "/", seconds(730*day), micros(30*time.Minute), 1, 0, 0),
|
||||
firefoxFixtureInsertCookie("session", "ephemeral", "app."+site, "/", 0, micros(40*time.Minute), 1, 1, 256),
|
||||
)
|
||||
|
||||
fixtureSQLite(t, filepath.Join(dir, "places.sqlite"),
|
||||
firefoxFixturePlacesSchema, firefoxFixtureBookmarksSchema, firefoxFixtureAnnoAttributesSchema, firefoxFixtureAnnosSchema,
|
||||
firefoxFixtureInsertPlace(1, link("www", "/"), "Home", 42, micros(3*time.Hour)),
|
||||
firefoxFixtureInsertPlace(2, link("docs", "/guide?q=go&lang=en"), `Guide, "quoted" & <b>bold</b>`, 7, micros(4*time.Hour)),
|
||||
firefoxFixtureInsertPlace(3, link("news", "/ja"), "ニュース", 3, micros(5*time.Hour)),
|
||||
firefoxFixtureInsertPlace(4, link("docs", "/"), "Docs", 0, 0),
|
||||
firefoxFixtureInsertPlace(5, link("news", "/long-read"), "Long read", 1, micros(9*time.Hour)),
|
||||
firefoxFixtureInsertPlace(6, link("files", "/report.pdf"), "", 1, micros(6*time.Hour)),
|
||||
firefoxFixtureInsertPlace(7, link("files", "/archive.tar.gz"), "", 1, micros(7*time.Hour)),
|
||||
firefoxFixtureInsertPlace(8, link("shop", "/menu"), "Café menu", 2, micros(10*time.Hour)),
|
||||
firefoxFixtureInsertPlace(9, link("files", "/setup.exe"), "", 1, micros(7*time.Hour+30*time.Minute)),
|
||||
|
||||
firefoxFixtureInsertBookmark(1, 2, 0, 0, 0, "", "root________", micros(0)),
|
||||
firefoxFixtureInsertBookmark(2, 2, 0, 1, 0, "menu", "menu________", micros(0)),
|
||||
firefoxFixtureInsertBookmark(3, 2, 0, 1, 1, "toolbar", "toolbar_____", micros(0)),
|
||||
firefoxFixtureInsertBookmark(4, 2, 0, 1, 2, "tags", "tags________", micros(0)),
|
||||
firefoxFixtureInsertBookmark(5, 2, 0, 1, 3, "unfiled", "unfiled_____", micros(0)),
|
||||
firefoxFixtureInsertBookmark(6, 2, 0, 1, 4, "mobile", "mobile______", micros(0)),
|
||||
firefoxFixtureInsertBookmark(7, 1, 4, 3, 0, "Docs", "bookmark0007", micros(8*time.Hour)),
|
||||
firefoxFixtureInsertBookmark(8, 2, 0, 3, 1, "Reading", "folder000008", micros(0)),
|
||||
firefoxFixtureInsertBookmark(9, 1, 5, 8, 0, "Long read <with> & tags", "bookmark0009", micros(9*time.Hour)),
|
||||
firefoxFixtureInsertBookmark(10, 3, 0, 3, 2, "", "separator010", micros(0)),
|
||||
firefoxFixtureInsertBookmark(11, 1, 8, 2, 0, "Café menu", "bookmark0011", micros(10*time.Hour)),
|
||||
firefoxFixtureInsertBookmark(12, 1, 1, 5, 0, "", "bookmark0012", micros(11*time.Hour)),
|
||||
|
||||
`INSERT INTO moz_anno_attributes (id, name) VALUES (1, 'downloads/destinationFileURI'), (2, 'downloads/metaData')`,
|
||||
firefoxFixtureInsertAnno(6, 1, "file:///C:/Users/alice/Downloads/report.pdf", micros(6*time.Hour)),
|
||||
firefoxFixtureInsertAnno(6, 2, fmt.Sprintf(`{"state":1,"deleted":false,"endTime":%d,"fileSize":52344}`,
|
||||
millis(6*time.Hour+3*time.Second)), micros(6*time.Hour)),
|
||||
firefoxFixtureInsertAnno(7, 1, "file:///home/alice/Downloads/archive.tar.gz", micros(7*time.Hour)),
|
||||
firefoxFixtureInsertAnno(7, 2, fmt.Sprintf(`{"state":1,"deleted":false,"endTime":%d,"fileSize":1048576}`,
|
||||
millis(7*time.Hour+time.Minute)), micros(7*time.Hour)),
|
||||
firefoxFixtureInsertAnno(9, 1, "file:///Users/alice/Downloads/setup.exe", micros(7*time.Hour+30*time.Minute)),
|
||||
)
|
||||
|
||||
fixtureWrite(t, filepath.Join(dir, "extensions.json"), firefoxFixtureExtensions)
|
||||
|
||||
fixtureSQLite(t, filepath.Join(dir, "webappsstore.sqlite"), firefoxFixtureWebappsstoreSchema,
|
||||
firefoxFixtureInsertStorage(firefoxFixtureOriginKey("https", "app."+site, 443), "greeting", "café"),
|
||||
firefoxFixtureInsertStorage(firefoxFixtureOriginKey("https", "app."+site, 443), "言語", "日本語"),
|
||||
firefoxFixtureInsertStorage(firefoxFixtureOriginKey("http", "shop."+site, 8080), "cart", `{"items":2}`),
|
||||
)
|
||||
}
|
||||
|
||||
// The template goes through the decoder's own parser and Encrypt, so only the ASN.1 layout is spelled out here.
|
||||
func firefoxFixtureSeal(t *testing.T, marshal func() ([]byte, error), ciphertext *[]byte, key, plaintext []byte) []byte {
|
||||
t.Helper()
|
||||
template, err := marshal()
|
||||
require.NoError(t, err)
|
||||
pbe, err := crypto.NewASN1PBE(template)
|
||||
require.NoError(t, err)
|
||||
*ciphertext, err = pbe.Encrypt(key, plaintext)
|
||||
require.NoError(t, err)
|
||||
sealed, err := marshal()
|
||||
require.NoError(t, err)
|
||||
return sealed
|
||||
}
|
||||
|
||||
type firefoxFixturePBES2 struct {
|
||||
Algorithm struct {
|
||||
OID asn1.ObjectIdentifier
|
||||
Params struct {
|
||||
KDF struct {
|
||||
OID asn1.ObjectIdentifier
|
||||
Params struct {
|
||||
Salt []byte
|
||||
Iterations int
|
||||
KeyLength int
|
||||
PRF struct{ OID asn1.ObjectIdentifier }
|
||||
}
|
||||
}
|
||||
Cipher struct {
|
||||
OID asn1.ObjectIdentifier
|
||||
IV []byte
|
||||
}
|
||||
}
|
||||
}
|
||||
Ciphertext []byte
|
||||
}
|
||||
|
||||
func firefoxFixturePBES2Seal(t *testing.T, globalSalt []byte, seed string, plaintext []byte) []byte {
|
||||
t.Helper()
|
||||
var pbe firefoxFixturePBES2
|
||||
pbe.Algorithm.OID = oidPBES2
|
||||
kdf := &pbe.Algorithm.Params.KDF
|
||||
kdf.OID = oidPBKDF2
|
||||
kdf.Params.Salt = firefoxFixtureBytes(seed+"/salt", 32)
|
||||
kdf.Params.Iterations = 1
|
||||
kdf.Params.KeyLength = 32
|
||||
kdf.Params.PRF.OID = oidHMACWithSHA256
|
||||
pbe.Algorithm.Params.Cipher.OID = oidAES256CBC
|
||||
pbe.Algorithm.Params.Cipher.IV = firefoxFixtureBytes(seed+"/iv", 14)
|
||||
return firefoxFixtureSeal(t, func() ([]byte, error) { return asn1.Marshal(pbe) }, &pbe.Ciphertext, globalSalt, plaintext)
|
||||
}
|
||||
|
||||
type firefoxFixtureLoginPBE struct {
|
||||
KeyID []byte
|
||||
Cipher struct {
|
||||
OID asn1.ObjectIdentifier
|
||||
IV []byte
|
||||
}
|
||||
Ciphertext []byte
|
||||
}
|
||||
|
||||
func firefoxFixtureLoginSeal(t *testing.T, key []byte, seed, plaintext string) string {
|
||||
t.Helper()
|
||||
pbe := firefoxFixtureLoginPBE{KeyID: firefoxFixtureKeyID}
|
||||
if len(key) == 24 {
|
||||
pbe.Cipher.OID = oidDESEDE3CBC
|
||||
pbe.Cipher.IV = firefoxFixtureBytes(seed, 8)
|
||||
} else {
|
||||
pbe.Cipher.OID = oidAES256CBC
|
||||
pbe.Cipher.IV = firefoxFixtureBytes(seed, 16)
|
||||
}
|
||||
sealed := firefoxFixtureSeal(t, func() ([]byte, error) { return asn1.Marshal(pbe) }, &pbe.Ciphertext, key, []byte(plaintext))
|
||||
return base64.StdEncoding.EncodeToString(sealed)
|
||||
}
|
||||
|
||||
func firefoxFixtureBytes(seed string, n int) []byte {
|
||||
sum := sha256.Sum256([]byte(seed))
|
||||
return sum[:n]
|
||||
}
|
||||
|
||||
// webappsstore2 stores the host reversed, so a domain and its subdomains share a key prefix.
|
||||
func firefoxFixtureOriginKey(scheme, host string, port int) string {
|
||||
reversed := []byte(host)
|
||||
for i, j := 0, len(reversed)-1; i < j; i, j = i+1, j-1 {
|
||||
reversed[i], reversed[j] = reversed[j], reversed[i]
|
||||
}
|
||||
return fmt.Sprintf("%s.:%s:%d", reversed, scheme, port)
|
||||
}
|
||||
|
||||
func firefoxFixtureText(s string) string {
|
||||
if s == "" {
|
||||
return "NULL"
|
||||
}
|
||||
return "'" + s + "'"
|
||||
}
|
||||
|
||||
func firefoxFixtureInsertCookie(name, value, host, path string, expiry, creationTime int64, secure, httpOnly, sameSite int) string {
|
||||
return fmt.Sprintf(
|
||||
`INSERT INTO moz_cookies (originAttributes, name, value, host, path, expiry, lastAccessed, creationTime,
|
||||
isSecure, isHttpOnly, sameSite, rawSameSite, schemeMap)
|
||||
VALUES ('', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, %d, 2)`,
|
||||
name, value, host, path, expiry, creationTime, creationTime, secure, httpOnly, sameSite, sameSite,
|
||||
)
|
||||
}
|
||||
|
||||
func firefoxFixtureInsertPlace(id int, url, title string, visitCount int, lastVisitDate int64) string {
|
||||
lastVisit := "NULL"
|
||||
if lastVisitDate != 0 {
|
||||
lastVisit = fmt.Sprint(lastVisitDate)
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
`INSERT INTO moz_places (id, url, title, rev_host, visit_count, last_visit_date, guid, url_hash)
|
||||
VALUES (%d, '%s', %s, '', %d, %s, 'place%07d', 0)`,
|
||||
id, url, firefoxFixtureText(title), visitCount, lastVisit, id,
|
||||
)
|
||||
}
|
||||
|
||||
func firefoxFixtureInsertBookmark(id, bookmarkType, fk, parent, position int, title, guid string, dateAdded int64) string {
|
||||
fkValue := "NULL"
|
||||
if fk != 0 {
|
||||
fkValue = fmt.Sprint(fk)
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
`INSERT INTO moz_bookmarks (id, type, fk, parent, position, title, dateAdded, lastModified, guid)
|
||||
VALUES (%d, %d, %s, %d, %d, %s, %d, %d, '%s')`,
|
||||
id, bookmarkType, fkValue, parent, position, firefoxFixtureText(title), dateAdded, dateAdded, guid,
|
||||
)
|
||||
}
|
||||
|
||||
func firefoxFixtureInsertAnno(placeID, attributeID int, content string, dateAdded int64) string {
|
||||
return fmt.Sprintf(
|
||||
`INSERT INTO moz_annos (place_id, anno_attribute_id, content, flags, expiration, type, dateAdded, lastModified)
|
||||
VALUES (%d, %d, '%s', 0, 4, 3, %d, %d)`,
|
||||
placeID, attributeID, content, dateAdded, dateAdded,
|
||||
)
|
||||
}
|
||||
|
||||
func firefoxFixtureInsertStorage(originKey, key, value string) string {
|
||||
return fmt.Sprintf(
|
||||
`INSERT INTO webappsstore2 (originAttributes, originKey, scope, key, value) VALUES ('', '%s', '', '%s', '%s')`,
|
||||
originKey, key, value,
|
||||
)
|
||||
}
|
||||
|
||||
const firefoxFixtureMetaDataSchema = `CREATE TABLE metaData (id PRIMARY KEY UNIQUE ON CONFLICT REPLACE, item1, item2)`
|
||||
|
||||
const firefoxFixtureNSSPrivateSchema = `CREATE TABLE nssPrivate (id PRIMARY KEY UNIQUE ON CONFLICT ABORT, a11, a102)`
|
||||
|
||||
const firefoxFixtureCookiesSchema = `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 firefoxFixturePlacesSchema = `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 firefoxFixtureBookmarksSchema = `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 firefoxFixtureAnnoAttributesSchema = `CREATE TABLE moz_anno_attributes (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(32) UNIQUE NOT NULL
|
||||
)`
|
||||
|
||||
const firefoxFixtureAnnosSchema = `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 firefoxFixtureWebappsstoreSchema = `CREATE TABLE webappsstore2 (
|
||||
originAttributes TEXT,
|
||||
originKey TEXT,
|
||||
scope TEXT,
|
||||
key TEXT,
|
||||
value TEXT
|
||||
)`
|
||||
|
||||
const firefoxFixtureLogins = `{
|
||||
"nextId": 4,
|
||||
"logins": [
|
||||
{
|
||||
"id": 1,
|
||||
"hostname": "https://accounts.%[1]s",
|
||||
"httpRealm": null,
|
||||
"formSubmitURL": "https://login.%[1]s",
|
||||
"usernameField": "username",
|
||||
"passwordField": "password",
|
||||
"encryptedUsername": "%[2]s",
|
||||
"encryptedPassword": "%[3]s",
|
||||
"encType": 1,
|
||||
"timeCreated": %[4]d,
|
||||
"timesUsed": 3
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"hostname": "https://shop.%[1]s",
|
||||
"httpRealm": null,
|
||||
"formSubmitURL": "",
|
||||
"usernameField": "email",
|
||||
"passwordField": "password",
|
||||
"encryptedUsername": "%[5]s",
|
||||
"encryptedPassword": "%[6]s",
|
||||
"encType": 1,
|
||||
"timeCreated": %[7]d,
|
||||
"timesUsed": 1
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"hostname": "https://intranet.%[1]s",
|
||||
"httpRealm": "Staff only",
|
||||
"formSubmitURL": null,
|
||||
"usernameField": "",
|
||||
"passwordField": "",
|
||||
"encryptedUsername": "%[8]s",
|
||||
"encryptedPassword": "%[9]s",
|
||||
"encType": 1,
|
||||
"timeCreated": %[10]d,
|
||||
"timesUsed": 7
|
||||
}
|
||||
],
|
||||
"potentiallyVulnerablePasswords": [],
|
||||
"dismissedBreachAlertsByLoginGUID": {},
|
||||
"version": 3
|
||||
}`
|
||||
|
||||
const firefoxFixtureExtensions = `{
|
||||
"schemaVersion": 36,
|
||||
"addons": [
|
||||
{
|
||||
"id": "tab-organizer@tabs.example",
|
||||
"version": "2.4.1",
|
||||
"type": "extension",
|
||||
"defaultLocale": {
|
||||
"name": "Tab Organizer",
|
||||
"description": "Groups tabs by site, \"neatly\" & <fast>",
|
||||
"creator": "Tabs Example",
|
||||
"homepageURL": "https://tabs.example/"
|
||||
},
|
||||
"active": true,
|
||||
"userDisabled": false,
|
||||
"location": "app-profile"
|
||||
},
|
||||
{
|
||||
"id": "{4b5ac9d3-1f2e-4d6c-9a8b-7c6d5e4f3a2b}",
|
||||
"version": "0.9.0",
|
||||
"type": "extension",
|
||||
"defaultLocale": {"name": "Reader Mode", "description": "Distraction-free reading", "homepageURL": null},
|
||||
"active": false,
|
||||
"userDisabled": true,
|
||||
"location": "app-profile"
|
||||
},
|
||||
{
|
||||
"id": "formautofill@mozilla.org",
|
||||
"version": "1.0.1",
|
||||
"type": "extension",
|
||||
"defaultLocale": {"name": "Form Autofill", "description": "Autofill forms with saved profiles.", "homepageURL": null},
|
||||
"active": true,
|
||||
"location": "app-system-defaults"
|
||||
},
|
||||
{
|
||||
"id": "default-theme@mozilla.org",
|
||||
"version": "1.3",
|
||||
"type": "theme",
|
||||
"defaultLocale": {"name": "System theme — auto", "description": "Follow the operating system setting.", "homepageURL": null},
|
||||
"active": true,
|
||||
"location": "app-builtin"
|
||||
}
|
||||
]
|
||||
}`
|
||||
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func fixtureWrite(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
|
||||
}
|
||||
|
||||
func fixtureSQLite(t *testing.T, path string, stmts ...string) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
|
||||
db, err := sql.Open("sqlite", path)
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
for _, stmt := range stmts {
|
||||
_, err = db.Exec(stmt)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
@@ -25,27 +25,9 @@ func TestPipelineGolden(t *testing.T) {
|
||||
keys[ibrowser.DirID(inst.key)] = chromiumFixtureKeys
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
format string
|
||||
golden string
|
||||
jsonFallback bool
|
||||
}{
|
||||
{format: "csv", golden: "extract-csv.golden"},
|
||||
{format: "json", golden: "extract-json.golden"},
|
||||
{format: "cookie-editor", golden: "extract-cookie-editor.golden", jsonFallback: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.format, func(t *testing.T) {
|
||||
out := pipelineGoldenRun(t, home, keys, tt.format)
|
||||
got := bundleDir(t, out)
|
||||
if tt.jsonFallback {
|
||||
assertJSONFallback(t, out, pipelineGoldenRun(t, home, keys, "json"))
|
||||
got = bundleFiles(t, out, "cookie.json")
|
||||
}
|
||||
assertGolden(t, tt.golden, got)
|
||||
})
|
||||
}
|
||||
assertExtractGoldens(t, "extract", func(t *testing.T, format string) string {
|
||||
return pipelineGoldenRun(t, home, keys, format)
|
||||
})
|
||||
}
|
||||
|
||||
func pipelineGoldenRun(t *testing.T, home string, keys map[ibrowser.DirID]masterkey.Set, format string) string {
|
||||
|
||||
@@ -68,7 +68,7 @@ func restoreWantFiles(t *testing.T, data string) map[string]string {
|
||||
}
|
||||
toVaultKeys := strings.NewReplacer(stamps...)
|
||||
|
||||
files := readDirFiles(t, extractGoldenRun(t, data, "json"))
|
||||
files := readDirFiles(t, extractGoldenRun(t, chromiumFixtureBrowsers(t, data), "json"))
|
||||
for name, content := range files {
|
||||
restamped := toVaultKeys.Replace(content)
|
||||
require.NotEqualf(t, content, restamped, "%s carries no display-name stamp to restamp", name)
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/moond4rk/plist"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/browser/safari"
|
||||
"github.com/moond4rk/hackbrowserdata/types"
|
||||
)
|
||||
|
||||
const (
|
||||
safariFixtureWorkUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
|
||||
safariFixtureUntitledUUID = "9A1B2C3D-4E5F-4A6B-8C7D-0E1F2A3B4C5D"
|
||||
)
|
||||
|
||||
var safariFixtureStart = time.Date(2024, 3, 1, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
func safariFixtureBrowsers(t *testing.T, home string) []browser.Browser {
|
||||
t.Helper()
|
||||
b, err := safari.NewBrowser(types.BrowserConfig{
|
||||
Key: "safari",
|
||||
Name: "Safari",
|
||||
Kind: types.Safari,
|
||||
UserDataDir: filepath.Join(home, "Library", "Safari"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, b)
|
||||
return []browser.Browser{b}
|
||||
}
|
||||
|
||||
func safariFixtureLibrary(t *testing.T, library string) {
|
||||
t.Helper()
|
||||
at := safariFixtureStart.Add
|
||||
visit := func(offset time.Duration) float64 { return safariFixtureCoreData(at(offset)) }
|
||||
day := 24 * time.Hour
|
||||
legacyHome := filepath.Join(library, "Safari")
|
||||
container := filepath.Join(library, "Containers", "com.apple.Safari", "Data", "Library")
|
||||
workStore := filepath.Join(container, "WebKit", "WebsiteDataStore", strings.ToLower(safariFixtureWorkUUID))
|
||||
|
||||
fixtureSQLite(t, filepath.Join(container, "Safari", "SafariTabs.db"), safariFixtureTabsSchema,
|
||||
`INSERT INTO bookmarks (id, parent, type, title, order_index, external_uuid, subtype) VALUES
|
||||
(1, 0, 1, 'Favorites', 0, 'Favorites', 0),
|
||||
(2, 0, 1, '', 1, 'DefaultProfile', 2),
|
||||
(3, 0, 1, 'Work', 2, '`+safariFixtureWorkUUID+`', 2),
|
||||
(4, 0, 1, NULL, 3, '`+safariFixtureUntitledUUID+`', 2)`)
|
||||
|
||||
fixtureSQLite(t, filepath.Join(legacyHome, "History.db"), safariFixtureHistoryItemsSchema, safariFixtureHistoryVisitsSchema,
|
||||
safariFixtureInsertHistoryItem(1, "https://www.home.safari.test/", 42),
|
||||
safariFixtureInsertHistoryVisit(1, 1, visit(time.Hour), "Home (old)"),
|
||||
safariFixtureInsertHistoryVisit(2, 1, visit(3*time.Hour+500*time.Millisecond), "Home"),
|
||||
safariFixtureInsertHistoryItem(2, "https://docs.home.safari.test/guide?q=go&lang=en", 7),
|
||||
safariFixtureInsertHistoryVisit(3, 2, visit(4*time.Hour), `Guide, "quoted" & <b>bold</b>`),
|
||||
safariFixtureInsertHistoryItem(3, "https://news.home.safari.test/ja", 3),
|
||||
safariFixtureInsertHistoryVisit(4, 3, visit(5*time.Hour), "ニュース"),
|
||||
safariFixtureInsertHistoryItem(4, "https://files.home.safari.test/report.pdf", 0),
|
||||
)
|
||||
fixtureSQLite(t, filepath.Join(container, "Safari", "Profiles", safariFixtureWorkUUID, "History.db"),
|
||||
safariFixtureHistoryItemsSchema, safariFixtureHistoryVisitsSchema,
|
||||
safariFixtureInsertHistoryItem(1, "https://intranet.work.safari.test/", 12),
|
||||
safariFixtureInsertHistoryVisit(1, 1, visit(6*time.Hour), "Intranet"),
|
||||
safariFixtureInsertHistoryItem(2, "https://wiki.work.safari.test/onboarding", 2),
|
||||
safariFixtureInsertHistoryVisit(2, 2, visit(7*time.Hour), "Onboarding"),
|
||||
)
|
||||
fixtureSQLite(t, filepath.Join(container, "Safari", "Profiles", safariFixtureUntitledUUID, "History.db"),
|
||||
safariFixtureHistoryItemsSchema, safariFixtureHistoryVisitsSchema,
|
||||
safariFixtureInsertHistoryItem(1, "https://www.untitled.safari.test/", 1),
|
||||
safariFixtureInsertHistoryVisit(1, 1, visit(8*time.Hour), "Untitled"),
|
||||
)
|
||||
|
||||
fixtureWrite(t, filepath.Join(container, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t,
|
||||
[]safariFixtureCookie{
|
||||
{
|
||||
domain: ".home.safari.test", name: "SID", path: "/", value: "sid-home.safari.test", flags: 0x5,
|
||||
expires: at(365 * day), created: at(10*time.Minute + 750*time.Millisecond),
|
||||
},
|
||||
{
|
||||
domain: "www.home.safari.test", name: "prefs", path: "/settings", value: "theme=dark",
|
||||
expires: at(30 * day), created: at(20 * time.Minute),
|
||||
},
|
||||
},
|
||||
[]safariFixtureCookie{
|
||||
{
|
||||
domain: ".home.safari.test", name: "tracker", path: "/", value: "opt-out", flags: 0x1,
|
||||
expires: at(730 * day), created: at(30 * time.Minute),
|
||||
},
|
||||
{
|
||||
domain: "app.home.safari.test", name: "csrf", path: "/", value: "token-123", flags: 0x4,
|
||||
expires: at(day), created: at(40 * time.Minute),
|
||||
},
|
||||
},
|
||||
)))
|
||||
// Since macOS 14 the jar lives in the container, which wins over a leftover ~/Library/Cookies jar.
|
||||
fixtureWrite(t, filepath.Join(library, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t,
|
||||
[]safariFixtureCookie{{
|
||||
domain: "old.home.safari.test", name: "legacy", path: "/", value: "stale",
|
||||
expires: at(day), created: at(time.Minute),
|
||||
}},
|
||||
)))
|
||||
fixtureWrite(t, filepath.Join(workStore, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t,
|
||||
[]safariFixtureCookie{
|
||||
{
|
||||
domain: ".work.safari.test", name: "SSO", path: "/", value: "sso-work.safari.test", flags: 0x5,
|
||||
expires: at(7 * day), created: at(6 * time.Hour),
|
||||
},
|
||||
{
|
||||
domain: "wiki.work.safari.test", name: "lang", path: "/", value: "en",
|
||||
expires: at(90 * day), created: at(7 * time.Hour),
|
||||
},
|
||||
},
|
||||
)))
|
||||
|
||||
safariFixturePlist(t, filepath.Join(legacyHome, "Bookmarks.plist"), safariFixtureBookmarks)
|
||||
safariFixturePlist(t, filepath.Join(legacyHome, "Downloads.plist"), fmt.Sprintf(safariFixtureDownloads, safariFixtureWorkUUID))
|
||||
|
||||
defaultStore := filepath.Join(container, "WebKit", "WebsiteData", "Default")
|
||||
fixtureWrite(t, filepath.Join(defaultStore, "salt"), "\x8f\x1e\x5a\x33\x0c\xd4\x71\x9b")
|
||||
app := safariFixtureEndpoint{scheme: "https", host: "app.home.safari.test"}
|
||||
safariFixtureOrigin(t, defaultStore, app, app,
|
||||
[2]string{"greeting", "café"},
|
||||
[2]string{"言語", "日本語"},
|
||||
[2]string{"blob", strings.Repeat("x", 1100)},
|
||||
)
|
||||
safariFixtureOrigin(t, defaultStore,
|
||||
safariFixtureEndpoint{scheme: "https", host: "shop.home.safari.test"},
|
||||
safariFixtureEndpoint{scheme: "https", host: "cdn.home.safari.test", port: 8443},
|
||||
[2]string{"consent", "yes"},
|
||||
)
|
||||
idbOnly := safariFixtureEndpoint{scheme: "https", host: "idb.home.safari.test"}
|
||||
safariFixtureOrigin(t, defaultStore, idbOnly, idbOnly)
|
||||
workApp := safariFixtureEndpoint{scheme: "https", host: "app.work.safari.test"}
|
||||
safariFixtureOrigin(t, filepath.Join(workStore, "Origins"), workApp, workApp, [2]string{"greeting", "hello"})
|
||||
|
||||
safariFixturePlist(t, filepath.Join(container, "Safari", "AppExtensions", "Extensions.plist"), safariFixtureAppExtensions)
|
||||
safariFixturePlist(t, filepath.Join(container, "Safari", "WebExtensions", "Extensions.plist"), safariFixtureWebExtensions)
|
||||
}
|
||||
|
||||
func safariFixtureCoreData(ts time.Time) float64 {
|
||||
const unixToCoreDataSeconds = 978_307_200
|
||||
return float64(ts.UnixMilli())/1000 - unixToCoreDataSeconds
|
||||
}
|
||||
|
||||
// Safari writes binary plists; the fixtures keep XML so they read like plutil's XML output.
|
||||
func safariFixturePlist(t *testing.T, path, body string) {
|
||||
t.Helper()
|
||||
var v any
|
||||
_, err := plist.Unmarshal([]byte(`<plist version="1.0">`+body+`</plist>`), &v)
|
||||
require.NoError(t, err)
|
||||
data, err := plist.Marshal(v, plist.BinaryFormat)
|
||||
require.NoError(t, err)
|
||||
fixtureWrite(t, path, string(data))
|
||||
}
|
||||
|
||||
type safariFixtureCookie struct {
|
||||
domain, name, path, value string
|
||||
flags uint32
|
||||
expires, created time.Time
|
||||
}
|
||||
|
||||
type safariFixtureCookieHeader struct {
|
||||
Size uint32
|
||||
Version uint32
|
||||
Flags uint32
|
||||
HasPort uint32
|
||||
DomainOffset uint32
|
||||
NameOffset uint32
|
||||
PathOffset uint32
|
||||
ValueOffset uint32
|
||||
CommentOffset uint32
|
||||
EndOfHeader uint32
|
||||
Expires float64
|
||||
Created float64
|
||||
}
|
||||
|
||||
// Each argument is one page of the jar.
|
||||
func safariFixtureCookieFile(t *testing.T, pages ...[]safariFixtureCookie) []byte {
|
||||
t.Helper()
|
||||
encoded := make([][]byte, len(pages))
|
||||
file := binary.BigEndian.AppendUint32([]byte("cook"), uint32(len(pages)))
|
||||
for i, cookies := range pages {
|
||||
encoded[i] = safariFixtureCookiePage(t, cookies)
|
||||
file = binary.BigEndian.AppendUint32(file, uint32(len(encoded[i])))
|
||||
}
|
||||
for _, page := range encoded {
|
||||
file = append(file, page...)
|
||||
}
|
||||
return append(file, make([]byte, 8)...) // the checksum, which the decoder reads but never verifies
|
||||
}
|
||||
|
||||
func safariFixtureCookiePage(t *testing.T, cookies []safariFixtureCookie) []byte {
|
||||
t.Helper()
|
||||
records := make([][]byte, len(cookies))
|
||||
for i, c := range cookies {
|
||||
records[i] = safariFixtureCookieRecord(t, c)
|
||||
}
|
||||
page := binary.LittleEndian.AppendUint32([]byte{0x00, 0x00, 0x01, 0x00}, uint32(len(cookies)))
|
||||
offset := 4 + 4 + 4*len(cookies) + 4
|
||||
for _, r := range records {
|
||||
page = binary.LittleEndian.AppendUint32(page, uint32(offset))
|
||||
offset += len(r)
|
||||
}
|
||||
page = append(page, 0x00, 0x00, 0x00, 0x00)
|
||||
for _, r := range records {
|
||||
page = append(page, r...)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
func safariFixtureCookieRecord(t *testing.T, c safariFixtureCookie) []byte {
|
||||
t.Helper()
|
||||
header := safariFixtureCookieHeader{
|
||||
Flags: c.flags,
|
||||
Expires: safariFixtureCoreData(c.expires),
|
||||
Created: safariFixtureCoreData(c.created),
|
||||
}
|
||||
headerSize := uint32(binary.Size(header))
|
||||
var strs []byte
|
||||
for _, f := range []struct {
|
||||
offset *uint32
|
||||
value string
|
||||
}{
|
||||
{&header.DomainOffset, c.domain},
|
||||
{&header.NameOffset, c.name},
|
||||
{&header.PathOffset, c.path},
|
||||
{&header.ValueOffset, c.value},
|
||||
} {
|
||||
*f.offset = headerSize + uint32(len(strs))
|
||||
strs = append(append(strs, f.value...), 0x00)
|
||||
}
|
||||
header.Size = headerSize + uint32(len(strs))
|
||||
var b bytes.Buffer
|
||||
require.NoError(t, binary.Write(&b, binary.LittleEndian, header))
|
||||
return append(b.Bytes(), strs...)
|
||||
}
|
||||
|
||||
type safariFixtureEndpoint struct {
|
||||
scheme, host string
|
||||
port uint16
|
||||
}
|
||||
|
||||
// One partition of a WebKit origins root: top and frame differ for third-party storage, and an origin without
|
||||
// localStorage items keeps only its origin file.
|
||||
func safariFixtureOrigin(t *testing.T, root string, top, frame safariFixtureEndpoint, items ...[2]string) {
|
||||
t.Helper()
|
||||
dir := filepath.Join(root, safariFixtureHash(top), safariFixtureHash(frame))
|
||||
fixtureWrite(t, filepath.Join(dir, "origin"), string(append(safariFixtureOriginBlock(top), safariFixtureOriginBlock(frame)...)))
|
||||
if len(items) == 0 {
|
||||
return
|
||||
}
|
||||
stmts := []string{safariFixtureItemTableSchema}
|
||||
for _, item := range items {
|
||||
stmts = append(stmts, fmt.Sprintf(`INSERT INTO ItemTable (key, value) VALUES ('%s', x'%x')`, item[0], safariFixtureUTF16(item[1])))
|
||||
}
|
||||
fixtureSQLite(t, filepath.Join(dir, "LocalStorage", "localstorage.sqlite3"), stmts...)
|
||||
}
|
||||
|
||||
func safariFixtureHash(e safariFixtureEndpoint) string {
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("%s://%s:%d", e.scheme, e.host, e.port)))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func safariFixtureOriginBlock(e safariFixtureEndpoint) []byte {
|
||||
const latin1, defaultPort, explicitPort = 0x01, 0x00, 0x01
|
||||
var b []byte
|
||||
for _, s := range []string{e.scheme, e.host} {
|
||||
b = binary.LittleEndian.AppendUint32(b, uint32(len(s)))
|
||||
b = append(append(b, latin1), s...)
|
||||
}
|
||||
if e.port == 0 {
|
||||
return append(b, defaultPort)
|
||||
}
|
||||
return binary.LittleEndian.AppendUint16(append(b, explicitPort), e.port)
|
||||
}
|
||||
|
||||
func safariFixtureUTF16(s string) []byte {
|
||||
var b []byte
|
||||
for _, u := range utf16.Encode([]rune(s)) {
|
||||
b = binary.LittleEndian.AppendUint16(b, u)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func safariFixtureInsertHistoryItem(id int, url string, visitCount int) string {
|
||||
return fmt.Sprintf(`INSERT INTO history_items (id, url, visit_count) VALUES (%d, '%s', %d)`, id, url, visitCount)
|
||||
}
|
||||
|
||||
func safariFixtureInsertHistoryVisit(id, item int, visitTime float64, title string) string {
|
||||
return fmt.Sprintf(`INSERT INTO history_visits (id, history_item, visit_time, title) VALUES (%d, %d, %f, '%s')`,
|
||||
id, item, visitTime, title)
|
||||
}
|
||||
|
||||
const safariFixtureTabsSchema = `CREATE TABLE bookmarks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
parent INTEGER,
|
||||
type INTEGER,
|
||||
title TEXT,
|
||||
url TEXT,
|
||||
order_index INTEGER NOT NULL,
|
||||
external_uuid TEXT UNIQUE,
|
||||
subtype INTEGER DEFAULT 0
|
||||
)`
|
||||
|
||||
const safariFixtureHistoryItemsSchema = `CREATE TABLE history_items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
url TEXT NOT NULL UNIQUE,
|
||||
domain_expansion TEXT NULL,
|
||||
visit_count INTEGER NOT NULL DEFAULT 0,
|
||||
daily_visit_counts BLOB NOT NULL DEFAULT x'',
|
||||
weekly_visit_counts BLOB NULL,
|
||||
autocomplete_triggers BLOB NULL,
|
||||
should_recompute_derived_visit_counts INTEGER NOT NULL DEFAULT 1,
|
||||
visit_count_score INTEGER NOT NULL DEFAULT 0
|
||||
)`
|
||||
|
||||
const safariFixtureHistoryVisitsSchema = `CREATE TABLE history_visits (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
history_item INTEGER NOT NULL REFERENCES history_items(id),
|
||||
visit_time REAL NOT NULL,
|
||||
title TEXT NULL,
|
||||
load_successful BOOLEAN NOT NULL DEFAULT 1,
|
||||
http_non_get INTEGER NOT NULL DEFAULT 0,
|
||||
synthesized INTEGER NOT NULL DEFAULT 0,
|
||||
redirect_source INTEGER NULL,
|
||||
redirect_destination INTEGER NULL,
|
||||
origin INTEGER NOT NULL DEFAULT 0,
|
||||
generation INTEGER NOT NULL DEFAULT 0,
|
||||
attributes INTEGER NOT NULL DEFAULT 0,
|
||||
score INTEGER NOT NULL DEFAULT 0
|
||||
)`
|
||||
|
||||
const safariFixtureItemTableSchema = `CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`
|
||||
|
||||
const safariFixtureBookmarks = `<dict>
|
||||
<key>Children</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Title</key><string>History</string>
|
||||
<key>WebBookmarkIdentifier</key><string>History</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeProxy</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>Children</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>URIDictionary</key><dict><key>title</key><string>Docs</string></dict>
|
||||
<key>URLString</key><string>https://docs.home.safari.test/</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>Children</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>URIDictionary</key><dict><key>title</key><string>Long read <with> & tags</string></dict>
|
||||
<key>URLString</key><string>https://news.home.safari.test/long-read</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>Title</key><string>Reading</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>URIDictionary</key><dict><key>title</key><string>Home</string></dict>
|
||||
<key>URLString</key><string>https://www.home.safari.test/</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>Title</key><string>BookmarksBar</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>Children</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>URIDictionary</key><dict><key>title</key><string>Café menu</string></dict>
|
||||
<key>URLString</key><string>https://shop.home.safari.test/menu</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>Title</key><string>BookmarksMenu</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>Children</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>ReadingList</key><dict><key>PreviewText</key><string>A post worth saving.</string></dict>
|
||||
<key>URIDictionary</key><dict><key>title</key><string>Saved post</string></dict>
|
||||
<key>URLString</key><string>https://blog.home.safari.test/post</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>Title</key><string>Untitled entry</string>
|
||||
<key>URLString</key><string>https://blog.home.safari.test/draft</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeLeaf</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>Title</key><string>com.apple.ReadingList</string>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>Title</key><string></string>
|
||||
<key>WebBookmarkFileVersion</key><integer>1</integer>
|
||||
<key>WebBookmarkType</key><string>WebBookmarkTypeList</string>
|
||||
</dict>`
|
||||
|
||||
const safariFixtureDownloads = `<dict>
|
||||
<key>DownloadHistory</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>DownloadEntryIdentifier</key><string>6B3E1D2C-0A9F-4E8D-B7C6-A5F4E3D2C1B0</string>
|
||||
<key>DownloadEntryPath</key><string>/Users/alice/Downloads/report.pdf</string>
|
||||
<key>DownloadEntryProfileUUIDStringKey</key><string>DefaultProfile</string>
|
||||
<key>DownloadEntryProgressBytesSoFar</key><integer>52344</integer>
|
||||
<key>DownloadEntryProgressTotalToLoad</key><integer>52344</integer>
|
||||
<key>DownloadEntryRemoveWhenDoneKey</key><false/>
|
||||
<key>DownloadEntryURL</key><string>https://files.home.safari.test/report.pdf</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>DownloadEntryIdentifier</key><string>1C2D3E4F-5A6B-4C7D-8E9F-0A1B2C3D4E5F</string>
|
||||
<key>DownloadEntryPath</key><string>/Users/alice/Downloads/slides.key</string>
|
||||
<key>DownloadEntryProfileUUIDStringKey</key><string>%[1]s</string>
|
||||
<key>DownloadEntryProgressBytesSoFar</key><integer>1048576</integer>
|
||||
<key>DownloadEntryProgressTotalToLoad</key><integer>1048576</integer>
|
||||
<key>DownloadEntryRemoveWhenDoneKey</key><false/>
|
||||
<key>DownloadEntryURL</key><string>https://files.work.safari.test/slides.key</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>DownloadEntryIdentifier</key><string>F0E1D2C3-B4A5-4968-8776-5A4B3C2D1E0F</string>
|
||||
<key>DownloadEntryPath</key><string>/Users/alice/Downloads/archive.tar.gz</string>
|
||||
<key>DownloadEntryProgressBytesSoFar</key><integer>2048</integer>
|
||||
<key>DownloadEntryProgressTotalToLoad</key><integer>2048</integer>
|
||||
<key>DownloadEntryRemoveWhenDoneKey</key><true/>
|
||||
<key>DownloadEntryURL</key><string>https://files.home.safari.test/archive.tar.gz</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>`
|
||||
|
||||
const safariFixtureAppExtensions = `<dict>
|
||||
<key>com.example.Clipper.Extension (ABCDE12345)</key>
|
||||
<dict><key>Permissions</key><dict/></dict>
|
||||
</dict>`
|
||||
|
||||
const safariFixtureWebExtensions = `<dict>
|
||||
<key>com.example.Blocker.Extension (FGHIJ67890)</key>
|
||||
<dict><key>Enabled</key><true/></dict>
|
||||
<key>com.example.Reader.Extension (KLMNO13579)</key>
|
||||
<dict><key>Enabled</key><false/></dict>
|
||||
<key>com.example.Legacy</key>
|
||||
<dict><key>Enabled</key><true/></dict>
|
||||
</dict>`
|
||||
Reference in new issue
Block a user