Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ require (
github.com/moond4rk/binarycookies v1.0.3
github.com/moond4rk/keychainbreaker v0.2.6
github.com/moond4rk/plist v1.2.2
github.com/ppacher/go-dbus-keyring v1.0.1
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.1.0
github.com/stretchr/testify v1.12.1
Expand Down
3 changes: 0 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.2.4 h1:F2gUCy++NMIxGmo9J+z5le/+ZC8W1OgeR51P4i9ZB/U=
github.com/godbus/dbus/v5 v5.2.4/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
Expand Down Expand Up @@ -33,8 +32,6 @@ github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/ppacher/go-dbus-keyring v1.0.1 h1:dM4dMfP5w9MxY+foFHCQiN7izEGpFdKr3tZeMGmvqD0=
github.com/ppacher/go-dbus-keyring v1.0.1/go.mod h1:JEmkRwBVPBFkOHedAsoZALWmhNJxR/R/ykkFpbEHtGE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand Down
176 changes: 146 additions & 30 deletions internal/masterkey/retriever_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ package masterkey
import (
"context"
"crypto/sha1"
"errors"
"fmt"
"strings"
"time"

"github.com/godbus/dbus/v5"
keyring "github.com/ppacher/go-dbus-keyring"

"github.com/moond4rk/hackbrowserdata/internal/log"
)

// linuxParams follow https://source.chromium.org/chromium/chromium/src/+/main:components/os_crypt/os_crypt_linux.cc
Expand All @@ -26,52 +30,164 @@ type dbusRetriever struct{}

func (dbusRetriever) Version() Version { return V11 }

func (dbusRetriever) Retrieve(_ context.Context, locator Locator) ([]byte, error) {
storage := locator.SecretLabel
const (
secretServiceName = "org.freedesktop.secrets"
secretServicePath = "/org/freedesktop/secrets"
secretServiceIntf = "org.freedesktop.Secret.Service"
secretItemIntf = "org.freedesktop.Secret.Item"
secretSessionIntf = "org.freedesktop.Secret.Session"
propertiesGet = "org.freedesktop.DBus.Properties.Get"
secretCallTimeout = 10 * time.Second
)

var errKeyringLocked = errors.New("keyring or wallet is locked")

// dbusSecret is the org.freedesktop.Secret.Item.GetSecret reply; a plain session leaves Value unencrypted.
type dbusSecret struct {
Session dbus.ObjectPath
Parameters []byte
Value []byte
ContentType string
}

// searchQueries find the storage item by libsecret's schema (GNOME), KWallet's schema, and KWallet's entry-name
// attribute, the last independent of the schema label, which KWallet versions set inconsistently.
func searchQueries(label string) []map[string]string {
return []map[string]string{
{"xdg:schema": "chrome_libsecret_os_crypt_password_v2"},
{"xdg:schema": "org.qt.keychain"},
{"user": label},
}
}

// Retrieve looks the storage key up through the Secret Service's SearchItems, which resolves only live items, then
// reads each one by one so a stale path that errors is skipped (a whole-collection read aborts on it instead). A
// match hidden behind a locked wallet is reported as locked, not as not found.
func (dbusRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, secretCallTimeout)
defer cancel()

connection, err := dbus.SessionBus()
if err != nil {
return nil, fmt.Errorf("dbus session: %w", err)
}
service := connection.Object(secretServiceName, secretServicePath)

service, err := keyring.GetSecretService(connection)
session, err := openSecretSession(ctx, service)
if err != nil {
return nil, fmt.Errorf("secret service: %w", err)
return nil, err
}
defer closeSecretSession(connection, session)

session, err := service.OpenSession()
if err != nil {
return nil, fmt.Errorf("open session: %w", err)
sawLocked := false
for _, attrs := range searchQueries(locator.SecretLabel) {
secret, locked := findStorageSecret(ctx, connection, service, session, attrs, locator.SecretLabel)
if len(secret) > 0 {
return linuxParams.deriveKey(secret), nil
}
sawLocked = sawLocked || locked
}
defer session.Close()
if sawLocked {
return nil, fmt.Errorf("%q: %w", locator.SecretLabel, errKeyringLocked)
}
return nil, fmt.Errorf("%q: %w", locator.SecretLabel, errStorageNotFound)
}

collections, err := service.GetAllCollections()
if err != nil {
return nil, fmt.Errorf("get collections: %w", err)
func openSecretSession(ctx context.Context, service dbus.BusObject) (dbus.ObjectPath, error) {
call := service.CallWithContext(ctx, secretServiceIntf+".OpenSession", 0, "plain", dbus.MakeVariant(""))
if call.Err != nil {
return "", fmt.Errorf("open secret session: %w", call.Err)
}
var output dbus.Variant
var session dbus.ObjectPath
if err := call.Store(&output, &session); err != nil {
return "", fmt.Errorf("open secret session: %w", err)
}
return session, nil
}

func closeSecretSession(connection *dbus.Conn, session dbus.ObjectPath) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if call := connection.Object(secretServiceName, session).CallWithContext(ctx, secretSessionIntf+".Close", 0); call.Err != nil {
log.Debugf("close secret session: %v", call.Err)
}
}

for _, collection := range collections {
items, err := collection.GetAllItems()
if err != nil {
// findStorageSecret returns the first live item matching attrs whose label fits want, and whether a locked item hid a
// possible match (so the caller can report "locked" rather than "not found").
func findStorageSecret(
ctx context.Context, conn *dbus.Conn, service dbus.BusObject, session dbus.ObjectPath, attrs map[string]string, want string,
) ([]byte, bool) {
call := service.CallWithContext(ctx, secretServiceIntf+".SearchItems", 0, attrs)
if call.Err != nil {
log.Debugf("secret service SearchItems %v: %v", attrs, call.Err)
return nil, false
}
var unlocked, locked []dbus.ObjectPath
if err := call.Store(&unlocked, &locked); err != nil {
return nil, false
}
sawLocked := false
if len(locked) > 0 {
opened := unlockItems(ctx, service, locked)
unlocked = append(unlocked, opened...)
sawLocked = len(opened) < len(locked)
}
for _, path := range unlocked {
if !labelMatches(itemLabel(ctx, conn, path), want) {
continue
}
for _, item := range items {
label, err := item.GetLabel()
if err != nil {
continue
}
if label == storage {
secret, err := item.GetSecret(session.Path())
if err != nil {
return nil, fmt.Errorf("get secret for %s: %w", storage, err)
}
if len(secret.Value) > 0 {
return linuxParams.deriveKey(secret.Value), nil
}
}
if secret := itemSecret(ctx, conn, path, session); len(secret) > 0 {
return secret, sawLocked
}
}
return nil, sawLocked
}

// unlockItems unlocks only what opens without a prompt; a returned prompt path (not "/") means a GUI dialog is needed,
// which a non-interactive extraction skips rather than block on.
func unlockItems(ctx context.Context, service dbus.BusObject, locked []dbus.ObjectPath) []dbus.ObjectPath {
call := service.CallWithContext(ctx, secretServiceIntf+".Unlock", 0, locked)
if call.Err != nil {
return nil
}
var unlocked []dbus.ObjectPath
var prompt dbus.ObjectPath
if err := call.Store(&unlocked, &prompt); err != nil {
return nil
}
return unlocked
}

// labelMatches accepts the exact Secret Service label and KWallet's "<folder>/<entry>" form, where the entry is want.
func labelMatches(label, want string) bool {
return label == want || strings.HasSuffix(label, "/"+want)
}

return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound)
func itemLabel(ctx context.Context, conn *dbus.Conn, path dbus.ObjectPath) string {
call := conn.Object(secretServiceName, path).CallWithContext(ctx, propertiesGet, 0, secretItemIntf, "Label")
if call.Err != nil {
return ""
}
var value dbus.Variant
if err := call.Store(&value); err != nil {
return ""
}
label, _ := value.Value().(string)
return label
}

func itemSecret(ctx context.Context, conn *dbus.Conn, path, session dbus.ObjectPath) []byte {
call := conn.Object(secretServiceName, path).CallWithContext(ctx, secretItemIntf+".GetSecret", 0, session)
if call.Err != nil {
return nil
}
var secret dbusSecret
if err := call.Store(&secret); err != nil {
return nil
}
return secret.Value
}

// posixRetriever covers hosts without a keyring (headless, Docker, CI), mirroring Chromium's PosixKeyProvider.
Expand Down
8 changes: 8 additions & 0 deletions internal/masterkey/retriever_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,11 @@ func TestPlatformRetrievers_Linux(t *testing.T) {
assert.Equal(t, V10, platformRetrievers[0].Version())
assert.Equal(t, V11, platformRetrievers[1].Version())
}

func TestLabelMatches(t *testing.T) {
assert.True(t, labelMatches("Chrome Safe Storage", "Chrome Safe Storage"), "exact label")
assert.True(t, labelMatches("Chrome Keys/Chrome Safe Storage", "Chrome Safe Storage"), "KWallet folder/entry form")
assert.False(t, labelMatches("Chromium Safe Storage", "Chrome Safe Storage"), "a different browser must not match")
assert.False(t, labelMatches("Chromium Keys/Chromium Safe Storage", "Chrome Safe Storage"), "nor its folder/entry form")
assert.False(t, labelMatches("", "Chrome Safe Storage"), "an unreadable label must not match")
}
Loading