Skip to content
Merged
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
219 changes: 188 additions & 31 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,205 @@ type dbusRetriever struct{}

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

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

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

func (dbusRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, secretCallTimeout)
defer cancel()

service, err := newSecretService(ctx)
if err != nil {
return nil, fmt.Errorf("dbus session: %w", err)
return nil, err
}
defer service.Close()

service, err := keyring.GetSecretService(connection)
secret, err := findStorageSecret(ctx, service, locator.SecretLabel)
if err != nil {
return nil, fmt.Errorf("secret service: %w", err)
return nil, fmt.Errorf("%q: %w", locator.SecretLabel, err)
}
return linuxParams.deriveKey(secret), nil
}

session, err := service.OpenSession()
if err != nil {
return nil, fmt.Errorf("open session: %w", err)
// secretStore is what findStorageSecret needs from the Secret Service, so tests can stand in for D-Bus.
type secretStore interface {
searchItems(ctx context.Context, attributes map[string]string) (unlocked, locked []dbus.ObjectPath, err error)
unlock(ctx context.Context, items []dbus.ObjectPath) ([]dbus.ObjectPath, error)
itemLabel(ctx context.Context, item dbus.ObjectPath) (string, error)
itemSecret(ctx context.Context, item dbus.ObjectPath) ([]byte, error)
}

// 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(storage string) []map[string]string {
return []map[string]string{
{"xdg:schema": "chrome_libsecret_os_crypt_password_v2"},
{"xdg:schema": "org.qt.keychain"},
{"user": storage},
}
defer session.Close()
}

collections, err := service.GetAllCollections()
if err != nil {
return nil, fmt.Errorf("get collections: %w", err)
// findStorageSecret tries each query; a match behind a wallet that stays locked reads as locked, not as not found.
func findStorageSecret(ctx context.Context, store secretStore, storage string) ([]byte, error) {
locked := false
for _, attributes := range searchQueries(storage) {
secret, err := searchStorageSecret(ctx, store, attributes, storage)
switch {
case err == nil:
return secret, nil
case errors.Is(err, errKeyringLocked):
locked = true
case !errors.Is(err, errStorageNotFound):
log.Debugf("secret service %v: %v", attributes, err)
}
}
switch {
case ctx.Err() != nil:
return nil, fmt.Errorf("secret service lookup: %w", ctx.Err())
case locked:
return nil, errKeyringLocked
}
return nil, errStorageNotFound
}

for _, collection := range collections {
items, err := collection.GetAllItems()
// searchStorageSecret relies on SearchItems, which resolves only live items, and reads each match on its own, so a
// stale path that fails is skipped (a whole-collection read aborts on it instead).
func searchStorageSecret(ctx context.Context, store secretStore, attributes map[string]string, storage string) ([]byte, error) {
items, locked, err := store.searchItems(ctx, attributes)
if err != nil {
return nil, err
}
var opened []dbus.ObjectPath
if len(locked) > 0 {
opened, err = store.unlock(ctx, locked)
if err != nil {
log.Debugf("secret service: %v", err)
}
items = append(items, opened...)
}
for _, item := range items {
label, err := store.itemLabel(ctx, item)
if err != nil {
log.Debugf("secret item %s: %v", item, err)
continue
}
if !labelMatches(label, storage) {
continue
}
secret, err := store.itemSecret(ctx, item)
if err != nil {
log.Debugf("secret item %s: %v", item, err)
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 len(secret) > 0 {
return secret, nil
}
}
if len(opened) < len(locked) {
return nil, errKeyringLocked
}
return nil, errStorageNotFound
}

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

type secretService struct {
connection *dbus.Conn
object dbus.BusObject
session dbus.ObjectPath
}

func newSecretService(ctx context.Context) (*secretService, error) {
connection, err := connectSessionBus(ctx)
if err != nil {
return nil, fmt.Errorf("dbus session: %w", err)
}
service := &secretService{connection: connection, object: connection.Object(secretServiceName, secretServicePath)}
call := service.object.CallWithContext(ctx, secretServiceInterface+".OpenSession", 0, "plain", dbus.MakeVariant(""))
var output dbus.Variant
if err := call.Store(&output, &service.session); err != nil {
return nil, errors.Join(fmt.Errorf("open secret session: %w", err), connection.Close())
}
return service, nil
}

// connectSessionBus never launches a bus, unlike dbus.SessionBus, and ties the connection to ctx, so the deadline
// bounds connecting and every later call, Close included.
func connectSessionBus(ctx context.Context) (*dbus.Conn, error) {
connection, err := dbus.SessionBusPrivateNoAutoStartup(dbus.WithContext(ctx))
if err != nil {
return nil, err
}
if err := connection.Auth(nil); err != nil {
return nil, errors.Join(err, connection.Close())
}
if err := connection.Hello(); err != nil {
return nil, errors.Join(err, connection.Close())
}
return connection, nil
}

func (s *secretService) Close() error {
call := s.connection.Object(secretServiceName, s.session).Call(secretSessionInterface+".Close", 0)
return errors.Join(call.Err, s.connection.Close())
}

func (s *secretService) searchItems(ctx context.Context, attributes map[string]string) (unlocked, locked []dbus.ObjectPath, err error) {
call := s.object.CallWithContext(ctx, secretServiceInterface+".SearchItems", 0, attributes)
if err = call.Store(&unlocked, &locked); err != nil {
return nil, nil, fmt.Errorf("search items: %w", err)
}
return unlocked, locked, nil
}

// unlock keeps 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 (s *secretService) unlock(ctx context.Context, items []dbus.ObjectPath) ([]dbus.ObjectPath, error) {
call := s.object.CallWithContext(ctx, secretServiceInterface+".Unlock", 0, items)
var unlocked []dbus.ObjectPath
var prompt dbus.ObjectPath
if err := call.Store(&unlocked, &prompt); err != nil {
return nil, fmt.Errorf("unlock items: %w", err)
}
return unlocked, nil
}

func (s *secretService) itemLabel(ctx context.Context, item dbus.ObjectPath) (string, error) {
call := s.connection.Object(secretServiceName, item).CallWithContext(ctx, propertiesGet, 0, secretItemInterface, "Label")
var label string
if err := call.Store(&label); err != nil {
return "", fmt.Errorf("read label: %w", err)
}
return label, nil
}

func (s *secretService) itemSecret(ctx context.Context, item dbus.ObjectPath) ([]byte, error) {
call := s.connection.Object(secretServiceName, item).CallWithContext(ctx, secretItemInterface+".GetSecret", 0, s.session)
var reply dbusSecret
if err := call.Store(&reply); err != nil {
return nil, fmt.Errorf("get secret: %w", err)
}
return reply.Value, nil
}

return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound)
// 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
}

// posixRetriever covers hosts without a keyring (headless, Docker, CI), mirroring Chromium's PosixKeyProvider.
Expand Down
Loading
Loading