fix(masterkey): resolve Linux v11 keys via Secret Service (#705)

A stale GNOME keyring item aborted the collection read and exact labels missed KWallet's folder/entry form, so v11 keys read as not found; the lookup now searches live items over its own deadline-bound connection.

Refs #572, #161
This commit is contained in:
Roger authored and GitHub committed 2026-11-19 16:53:56 +08:00
1 parent b14b2c021a
commit 066dd15be1
4 files changed
+373 -40

No files matched your search

-1
View File
@@ -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
-3
View File
@@ -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=
@@ -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=
+193 -36
View File
@@ -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
@@ -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, err
}
defer service.Close()
secret, err := findStorageSecret(ctx, service, locator.SecretLabel)
if err != nil {
return nil, fmt.Errorf("%q: %w", locator.SecretLabel, err)
}
return linuxParams.deriveKey(secret), nil
}
// 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},
}
}
// 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
}
// 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
}
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
}
service, err := keyring.GetSecretService(connection)
// 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, fmt.Errorf("secret service: %w", err)
return nil, err
}
session, err := service.OpenSession()
if err != nil {
return nil, fmt.Errorf("open session: %w", err)
if err := connection.Auth(nil); err != nil {
return nil, errors.Join(err, connection.Close())
}
defer session.Close()
collections, err := service.GetAllCollections()
if err != nil {
return nil, fmt.Errorf("get collections: %w", err)
if err := connection.Hello(); err != nil {
return nil, errors.Join(err, connection.Close())
}
return connection, nil
}
for _, collection := range collections {
items, err := collection.GetAllItems()
if err != nil {
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
}
}
}
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
}
return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound)
// 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
}
// 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.
+180
View File
@@ -4,8 +4,11 @@ package masterkey
import (
"context"
"errors"
"strconv"
"testing"
"github.com/godbus/dbus/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -51,3 +54,180 @@ 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")
}
func TestFindStorageSecret(t *testing.T) {
const storage = "Chrome Safe Storage"
libsecret := map[string]string{"xdg:schema": "chrome_libsecret_os_crypt_password_v2"}
kwallet := map[string]string{"xdg:schema": "org.qt.keychain", "user": storage}
tests := []struct {
name string
store fakeSecretStore
want string
wantErr error
}{
{
name: "libsecret item",
store: fakeSecretStore{{attributes: libsecret, label: storage, secret: "gnome"}},
want: "gnome",
},
{
name: "KWallet folder/entry label",
store: fakeSecretStore{{attributes: kwallet, label: "Chrome Keys/" + storage, secret: "kde"}},
want: "kde",
},
{
name: "KWallet entry under another schema",
store: fakeSecretStore{
{attributes: map[string]string{"xdg:schema": "other", "user": storage}, label: "Chrome Keys/" + storage, secret: "kde"},
},
want: "kde",
},
{
name: "another browser's item",
store: fakeSecretStore{{attributes: libsecret, label: "Chromium Safe Storage", secret: "chromium"}},
wantErr: errStorageNotFound,
},
{
name: "stale path is skipped",
store: fakeSecretStore{
{attributes: libsecret, label: storage, stale: true},
{attributes: libsecret, label: storage, secret: "live"},
},
want: "live",
},
{
name: "locked item that opens without a prompt",
store: fakeSecretStore{{attributes: libsecret, label: storage, secret: "opened", locked: true, unlockable: true}},
want: "opened",
},
{
name: "wallet that stays locked",
store: fakeSecretStore{{attributes: libsecret, label: storage, secret: "hidden", locked: true}},
wantErr: errKeyringLocked,
},
{
name: "a later match wins over a locked wallet",
store: fakeSecretStore{
{attributes: libsecret, label: storage, secret: "hidden", locked: true},
{attributes: kwallet, label: "Chrome Keys/" + storage, secret: "kde"},
},
want: "kde",
},
{
name: "empty store",
wantErr: errStorageNotFound,
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
secret, err := findStorageSecret(context.Background(), testCase.store, storage)
if testCase.wantErr != nil {
require.ErrorIs(t, err, testCase.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, testCase.want, string(secret))
})
}
}
func TestFindStorageSecret_Timeout(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 0)
defer cancel()
store := fakeSecretStore{{attributes: map[string]string{"user": "Chrome Safe Storage"}, label: "Chrome Safe Storage", secret: "late"}}
_, err := findStorageSecret(ctx, store, "Chrome Safe Storage")
require.ErrorIs(t, err, context.DeadlineExceeded)
assert.NotErrorIs(t, err, errStorageNotFound, "a lookup that ran out of time must not read as not found")
}
// fakeItem is one Secret Service item: a locked one reads only once unlocked, and a stale one never does.
type fakeItem struct {
attributes map[string]string
label string
secret string
locked bool
unlockable bool
stale bool
}
type fakeSecretStore []fakeItem
func fakeItemPath(index int) dbus.ObjectPath {
return dbus.ObjectPath("/item/" + strconv.Itoa(index))
}
func (s fakeSecretStore) item(path dbus.ObjectPath) fakeItem {
for index, item := range s {
if fakeItemPath(index) == path {
return item
}
}
return fakeItem{stale: true}
}
func (s fakeSecretStore) searchItems(ctx context.Context, attributes map[string]string) (unlocked, locked []dbus.ObjectPath, err error) {
if ctx.Err() != nil {
return nil, nil, ctx.Err()
}
for index, item := range s {
if !hasAttributes(item.attributes, attributes) {
continue
}
if item.locked {
locked = append(locked, fakeItemPath(index))
} else {
unlocked = append(unlocked, fakeItemPath(index))
}
}
return unlocked, locked, nil
}
func (s fakeSecretStore) unlock(_ context.Context, items []dbus.ObjectPath) ([]dbus.ObjectPath, error) {
var opened []dbus.ObjectPath
for _, path := range items {
for index := range s {
if fakeItemPath(index) == path && s[index].unlockable {
s[index].locked = false
opened = append(opened, path)
}
}
}
return opened, nil
}
func (s fakeSecretStore) itemLabel(_ context.Context, path dbus.ObjectPath) (string, error) {
item := s.item(path)
if item.stale {
return "", errors.New("no such object")
}
return item.label, nil
}
func (s fakeSecretStore) itemSecret(_ context.Context, path dbus.ObjectPath) ([]byte, error) {
item := s.item(path)
switch {
case item.stale:
return nil, errors.New("no such object")
case item.locked:
return nil, errors.New("cannot get secret of a locked object")
}
return []byte(item.secret), nil
}
func hasAttributes(attributes, query map[string]string) bool {
for key, value := range query {
if attributes[key] != value {
return false
}
}
return true
}