Fix use-after-free when a database tab close is re-entered (#13598)

* Fix use-after-free when a database tab close is re-entered

Closing a database tab may spin a nested event loop while the widget
performs save-on-close (Database::save waits for its worker thread in
AsyncTask::waitForFuture). If DatabaseTabWidget::closeDatabaseTab is
re-entered for the same widget from within that nested loop (e.g. two
concurrent FdoSecrets prompts deleting the same collection),
QWidget::close() short-circuits on its internal is_closing flag and
reports success immediately, without delivering another close event.
This behavior is identical in Qt 5 (QWidgetPrivate::close_helper) and
Qt 6 (QWidgetPrivate::handleClose), so none of the downstream guards
(such as DatabaseWidget::lock's m_attemptingLock) ever run for the
re-entrant close. The re-entrant call then removed the tab and
scheduled deletion, and the DeferredDelete event executed inside the
still-running nested loop, destroying the widget while the outer
invocation was still using it; the outer call afterwards repeated
parts of the teardown (stale-index removeTab, deleteLater on the freed
widget, duplicate databaseClosed emission). The bug is long-standing
and was surfaced by scheduler timing under an ASan build with Qt 6.11.

Detected by ASan as a heap-use-after-free in DatabaseWidget::save()
during TestGuiFdoSecrets::testCollectionDeleteConcurrent.

- DatabaseTabWidget::closeDatabaseTab: track widgets with a close in
  progress; a re-entrant call returns false without side effects, and
  only the outermost invocation may remove the tab, schedule deletion,
  and emit databaseClosed (exactly once now). Re-resolve the tab index
  after close() since nested event loops may shift tabs.
- FdoSecrets: PromptBase::prompt now schedules promptSync only once;
  repeated Prompt() calls wait for the same Completed signal instead
  of running the prompt action multiple times.
- FdoSecrets: DeleteCollectionPrompt clears its collection reference on
  Collection::collectionAboutToDelete. The QPointer alone still sees a
  retired collection (removed from D-Bus, m_backend already reset)
  until its deleteLater is delivered, which would violate the
  invariant behind Q_ASSERT(m_backend) in Collection::doDelete. With
  the explicit clearing the invariant "non-null m_collection implies
  usable backend" holds again and the assert stays.
- TestGuiFdoSecrets::testCollectionDeleteConcurrent: fix the second
  prompt proxy accidentally created from the first prompt's path (the
  test was exercising a double-Prompt on one object rather than two
  concurrent prompts), and assert the fail-fast behavior: the losing
  concurrent prompt completes as dismissed while the winner performs
  the deletion.

* FdoSecrets: complete prompts whose collections retire mid-prompt

A Collection retires (removed from D-Bus, backend reset, deleteLater
scheduled) synchronously when its database closes. Prompts, however,
reference collections via QPointer from timer callbacks outside D-Bus
dispatch, and a QPointer still sees the retired object until its
deferred deletion is delivered. This left two holes, both reachable
when a collection goes away while a prompt targeting it is in flight
(e.g. a concurrent Collection.Delete from another client):

- LockCollectionsPrompt/UnlockPrompt could call doLock()/doUnlock() on
  a retired collection, hitting Q_ASSERT(m_backend) in debug builds.
- UnlockPrompt would hang forever: the retired collection never emits
  doneUnlockCollection (its service connections are severed on
  retirement), and the count-based completion condition could no
  longer be satisfied, so the Completed signal never fired and the
  client waited indefinitely. The same accounting also hung when an
  entry was already destroyed by the time promptSync ran.

Following the same principle as DeleteCollectionPrompt: restore the
invariant that a non-null collection reference is usable, instead of
relaxing the asserts.

- LockCollectionsPrompt clears retired collection references on
  collectionAboutToDelete; a retired collection is skipped exactly
  like a destroyed one.
- UnlockPrompt tracks awaited collections in an explicit pending set,
  pre-registered before issuing any doUnlock so that synchronous
  completions (already-unlocked databases) cannot prematurely trigger
  the item unlock step. Retirement is accounted as a rejection and
  re-evaluates completion, so the prompt always terminates.
- Add regression test testServiceUnlockConcurrentDelete covering the
  unlock/delete race; verified to fail (hang detected via signal spy
  timeout) without this fix.

* FdoSecrets: clean up unlock dialog bookkeeping when the widget dies

Service::m_unlockingDb tracks databases with an unlock dialog shown to
prevent duplicate dialogs. If the DatabaseWidget is destroyed while
its dialog is open (e.g. the database is deleted via a concurrent
D-Bus call), dialogFinished never fires for it and the entry stayed
forever, keyed by a dangling pointer. The pointer was only ever
compared, not dereferenced, but the stale entry permanently blocked
doUnlockAnyDatabaseInDialog (used by unlock-before-search), and a
future widget allocated at the same address would have been refused an
unlock dialog as well.

Track a cleanup connection on the widget's destroyed signal alongside
the existing databaseUnlocked oneshot, covering both the per-database
and the unlock-any-database flows. Extend the
testServiceUnlockConcurrentDelete regression test to reopen the
database after the concurrent delete and verify the unlock dialog
still appears; without the fix the test times out in SearchItems
waiting for a dialog that never shows.

---------

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
AetfandClaude Fable 5 authored and GitHub committed 2026-08-23 22:45:29 -04:00
1 parent 0e1510d71a
commit 30e1fa5dfb
8 files changed
+217 -18

No files matched your search

+75 -8
View File
@@ -71,6 +71,13 @@ namespace FdoSecrets
return ret;
}
// the prompt is already being processed, do not schedule another run.
// the ongoing one will emit the completed signal.
if (m_signalSent || m_scheduled) {
return {};
}
m_scheduled = true;
QWeakPointer<DBusClient> weak = client;
// execute the actual prompt method in event loop to avoid block this method
QTimer::singleShot(0, this, [this, weak, windowId]() {
@@ -113,6 +120,12 @@ namespace FdoSecrets
: PromptBase(parent)
, m_collection(coll)
{
// The QPointer alone is not enough: after Collection::removeFromDBus the
// collection lingers until its deleteLater is delivered, with m_backend
// already reset. Clear our reference as soon as the collection retires so
// that a non-null m_collection always implies a usable backend, which
// Collection::doDelete asserts on.
connect(coll, &Collection::collectionAboutToDelete, this, [this]() { m_collection = nullptr; });
}
PromptResult DeleteCollectionPrompt::promptSync(const DBusClientPtr&, const QString& windowId)
@@ -182,6 +195,16 @@ namespace FdoSecrets
m_collections.reserve(colls.size());
for (const auto& c : asConst(colls)) {
m_collections << c;
// clear the reference as soon as the collection retires, so promptSync
// never calls into a collection whose backend is already gone.
// A retired collection is skipped just like a destroyed one.
connect(c, &Collection::collectionAboutToDelete, this, [this, c]() {
for (auto& p : m_collections) {
if (p == c) {
p = nullptr;
}
}
});
}
}
@@ -211,6 +234,9 @@ namespace FdoSecrets
m_collections.reserve(colls.size());
for (const auto& coll : asConst(colls)) {
m_collections << coll;
// a collection may retire while we are waiting for its unlock outcome,
// in which case doneUnlockCollection will never fire for it.
connect(coll, &Collection::collectionAboutToDelete, this, [this, coll]() { collectionRetired(coll); });
}
for (const auto& item : asConst(items)) {
m_items[item->collection()] << item;
@@ -230,21 +256,32 @@ namespace FdoSecrets
m_windowId = windowId;
m_client = client;
// first unlock any collections
bool waitingForCollections = false;
// first unlock any collections.
// register everything we will wait for upfront: doUnlock may complete
// synchronously (already unlocked database), and the completion handler
// must not conclude that all collections are done while some have not
// even been issued yet.
for (const auto& c : asConst(m_collections)) {
if (c) {
m_pendingCollections << c.data();
} else {
// the collection retired or was destroyed since the prompt was created
m_numRejected += 1;
}
}
for (const auto& c : asConst(m_collections)) {
// skip entries that already resolved synchronously or retired mid-loop
if (c && m_pendingCollections.contains(c.data())) {
connect(c, &Collection::doneUnlockCollection, this, &UnlockPrompt::collectionUnlockFinished);
// doUnlock is nonblocking, execution will continue in collectionUnlockFinished
// it is ok to call doUnlock multiple times before it's actually unlocked by the user
c->doUnlock();
waitingForCollections = true;
}
}
// unlock items directly if no collection unlocking pending
// o.w. doing it in collectionUnlockFinished
if (!waitingForCollections) {
// o.w. doing it in collectionUnlockFinished or collectionRetired
if (m_pendingCollections.isEmpty()) {
unlockItems();
}
@@ -261,8 +298,8 @@ namespace FdoSecrets
// one shot
coll->disconnect(this);
if (!m_collections.contains(coll)) {
// should not happen
if (!m_pendingCollections.remove(coll)) {
// not awaiting this collection (already resolved or retired)
return;
}
@@ -275,14 +312,44 @@ namespace FdoSecrets
}
// if we got response for all collections
if (m_numRejected + m_unlocked.size() == m_collections.size()) {
if (m_pendingCollections.isEmpty()) {
// next step is to unlock items
unlockItems();
}
}
void UnlockPrompt::collectionRetired(Collection* coll)
{
// the collection is going away (already removed from DBus, backend reset);
// stop referencing it so no doUnlock/doneUnlockCollection is attempted on it
for (auto& p : m_collections) {
if (p == coll) {
p = nullptr;
}
}
m_items.remove(coll);
if (!m_pendingCollections.remove(coll)) {
// nothing was issued for it yet (promptSync not run) or it already resolved;
// promptSync accounts for cleared entries itself
return;
}
// treat as if the collection rejected the unlock
m_numRejected += 1;
if (m_pendingCollections.isEmpty()) {
unlockItems();
}
}
void UnlockPrompt::unlockItems()
{
// may be reached from multiple paths (last collection resolving vs retiring)
if (m_unlockItemsStarted) {
return;
}
m_unlockItemsStarted = true;
auto client = m_client.lock();
if (!client) {
// client already gone
+8
View File
@@ -22,6 +22,8 @@
#include "fdosecrets/dbus/DBusClient.h"
#include "fdosecrets/dbus/DBusObject.h"
#include <QSet>
class QWindow;
class DatabaseWidget;
@@ -112,6 +114,7 @@ namespace FdoSecrets
private:
bool m_signalSent = false;
bool m_scheduled = false;
};
class Collection;
@@ -169,6 +172,7 @@ namespace FdoSecrets
QVariant currentResult() const override;
void collectionUnlockFinished(bool accepted);
void collectionRetired(Collection* coll);
void itemUnlockFinished(const QHash<Entry*, AuthDecision>& results, AuthDecision forFutureEntries);
void unlockItems();
@@ -176,6 +180,10 @@ namespace FdoSecrets
QHash<Collection*, QList<QPointer<Item>>> m_items;
QHash<QUuid, Item*> m_entryToItems;
// collections whose doUnlock was issued and whose outcome is still awaited
QSet<Collection*> m_pendingCollections;
bool m_unlockItemsStarted = false;
QList<QDBusObjectPath> m_unlocked;
int m_numRejected = 0;
+18 -6
View File
@@ -580,9 +580,12 @@ namespace FdoSecrets
return;
}
// insert a dummy one here, just to prevent multiple dialogs
// the real one will be inserted in onDatabaseUnlockDialogFinished
m_unlockingDb[dbWidget] = {};
// insert the entry here already, just to prevent multiple dialogs.
// the connection on databaseUnlocked will be added in onDatabaseUnlockDialogFinished.
// if the widget is destroyed while its dialog is open, dialogFinished may never
// fire for it, so clean up on destruction as well.
m_unlockingDb[dbWidget].destroyedConn =
connect(dbWidget, &QObject::destroyed, this, [this, dbWidget]() { m_unlockingDb.remove(dbWidget); });
// actually show the dialog
m_databases->unlockDatabaseInDialog(dbWidget, DatabaseOpenDialog::Intent::None);
@@ -608,16 +611,25 @@ namespace FdoSecrets
if (!accepted) {
emit doneUnlockDatabaseInDialog(false, dbWidget);
m_unlockingAnyDatabase = false;
m_unlockingDb.remove(dbWidget);
disconnect(m_unlockingDb.take(dbWidget).destroyedConn);
} else {
// delay the done signal to when the database is actually done with unlocking
// this is a oneshot connection to prevent superfluous signals
auto conn = connect(dbWidget, &DatabaseWidget::databaseUnlocked, this, [dbWidget, this]() {
emit doneUnlockDatabaseInDialog(true, dbWidget);
m_unlockingAnyDatabase = false;
disconnect(m_unlockingDb.take(dbWidget));
auto entry = m_unlockingDb.take(dbWidget);
disconnect(entry.unlockedConn);
disconnect(entry.destroyedConn);
});
m_unlockingDb[dbWidget] = conn;
auto& entry = m_unlockingDb[dbWidget];
entry.unlockedConn = conn;
// the unlock-any-database flow arrives here without a prior entry,
// make sure widget destruction cleans it up in that case too
if (!entry.destroyedConn) {
entry.destroyedConn = connect(
dbWidget, &QObject::destroyed, this, [this, dbWidget]() { m_unlockingDb.remove(dbWidget); });
}
}
}
} // namespace FdoSecrets
+10 -1
View File
@@ -175,7 +175,16 @@ namespace FdoSecrets
bool m_insideEnsureDefaultAlias{false};
bool m_unlockingAnyDatabase{false};
// list of db currently has unlock dialog shown
QHash<const DatabaseWidget*, QMetaObject::Connection> m_unlockingDb{};
struct UnlockingDbEntry
{
// oneshot connection on databaseUnlocked, delaying the done signal
// until the database has actually finished unlocking
QMetaObject::Connection unlockedConn;
// cleanup in case the widget is destroyed while its dialog is open,
// otherwise the stale entry would block unlock dialogs forever
QMetaObject::Connection destroyedConn;
};
QHash<const DatabaseWidget*, UnlockingDbEntry> m_unlockingDb{};
QSet<const DatabaseWidget*> m_lockingDb{}; // list of db being locking
};
+20 -1
View File
@@ -385,8 +385,27 @@ bool DatabaseTabWidget::closeDatabaseTab(DatabaseWidget* dbWidget)
return false;
}
// Closing may spin a nested event loop (e.g. save-on-close waits for the worker
// thread in AsyncTask), from which this method can be re-entered for the same
// widget. QWidget::close() would then report success right away without
// delivering another close event, and deleting the widget here would leave the
// outer invocation operating on a destroyed widget. Let only the outermost
// invocation remove the tab and schedule deletion.
if (m_widgetsPendingClose.contains(dbWidget)) {
return false;
}
QString filePath = dbWidget->database()->filePath();
if (!dbWidget->close()) {
m_widgetsPendingClose.insert(dbWidget);
bool closed = dbWidget->close();
m_widgetsPendingClose.remove(dbWidget);
if (!closed) {
return false;
}
// the tab layout may have shifted while nested event loops ran during close
tabIndex = indexOf(dbWidget);
if (tabIndex < 0) {
return false;
}
+2
View File
@@ -23,6 +23,7 @@
#include "gui/MessageWidget.h"
#include "wizard/ImportWizard.h"
#include <QSet>
#include <QTabWidget>
#include <QTimer>
@@ -127,6 +128,7 @@ private:
QPointer<ImportWizard> m_importWizard;
QTimer m_lockDelayTimer;
bool m_databaseOpenInProgress;
QSet<DatabaseWidget*> m_widgetsPendingClose;
};
#endif // KEEPASSXC_DATABASETABWIDGET_H
+83 -2
View File
@@ -586,6 +586,84 @@ void TestGuiFdoSecrets::testServiceUnlockDatabaseConcurrent()
DBUS_COMPARE(coll->locked(), false);
}
void TestGuiFdoSecrets::testServiceUnlockConcurrentDelete()
{
lockDatabaseInBackend();
auto service = enableService();
VERIFY(service);
auto coll = getDefaultCollection(service);
VERIFY(coll);
DBUS_GET2(unlocked, promptPath, service->Unlock({QDBusObjectPath(coll->path())}));
COMPARE(unlocked, {});
auto prompt = getProxy<PromptProxy>(promptPath);
VERIFY(prompt);
QSignalSpy spyPromptCompleted(prompt.data(), SIGNAL(Completed(bool, QDBusVariant)));
VERIFY(spyPromptCompleted.isValid());
// show the unlock dialog, but do not interact with it
DBUS_VERIFY(prompt->Prompt(""));
VERIFY(waitForSignal(spyPromptCompleted, 0));
// while the unlock prompt is waiting for the user, the collection gets deleted
DBUS_GET(deletePromptPath, coll->Delete());
auto deletePrompt = getProxy<PromptProxy>(deletePromptPath);
VERIFY(deletePrompt);
QSignalSpy spyDeletePromptCompleted(deletePrompt.data(), SIGNAL(Completed(bool, QDBusVariant)));
VERIFY(spyDeletePromptCompleted.isValid());
DBUS_VERIFY(deletePrompt->Prompt(""));
// the deletion completes
VERIFY(waitForSignal(spyDeletePromptCompleted, 1));
{
auto args = spyDeletePromptCompleted.takeFirst();
COMPARE(args.count(), 2);
COMPARE(args.at(0).toBool(), false);
}
// the unlock prompt completes as dismissed with nothing unlocked, instead of
// waiting forever for a collection that no longer exists
VERIFY(waitForSignal(spyPromptCompleted, 1));
{
auto args = spyPromptCompleted.takeFirst();
COMPARE(args.count(), 2);
COMPARE(args.at(0).toBool(), true);
auto unlockedResult = getSignalVariantArgument<QList<QDBusObjectPath>>(args.at(1));
VERIFY(unlockedResult.isEmpty());
}
// dismiss the leftover unlock dialog so it does not interfere with other tests
auto dbOpenDlg = m_tabWidget->findChild<DatabaseOpenDialog*>();
if (dbOpenDlg && dbOpenDlg->isVisible()) {
dbOpenDlg->reject();
processEvents();
}
// reopen the database; the service must still be able to show unlock dialogs.
// A stale Service::m_unlockingDb entry keyed by the destroyed widget used to
// block the unlock-any-database dialog forever.
m_tabWidget->addDatabaseTab(m_dbFile->fileName(), false, "a");
m_dbWidget = m_tabWidget->currentDatabaseWidget();
m_db = m_dbWidget->database();
processEvents();
auto entries = m_db->rootGroup()->entriesRecursive();
VERIFY(!entries.isEmpty());
auto title = entries.first()->title();
lockDatabaseInBackend();
FdoSecrets::settings()->setUnlockBeforeSearch(true);
bool unlockDialogWorks = false;
QTimer::singleShot(50, [&]() { unlockDialogWorks = driveUnlockDialog(); });
DBUS_GET2(unlockedItems, lockedItems, service->SearchItems({{"Title", title}}));
VERIFY(unlockDialogWorks);
COMPARE(lockedItems, {});
COMPARE(unlockedItems.size(), 1);
}
void TestGuiFdoSecrets::testServiceUnlockItems()
{
FdoSecrets::settings()->setConfirmAccessItem(true);
@@ -1003,7 +1081,7 @@ void TestGuiFdoSecrets::testCollectionDeleteConcurrent()
// before interacting with the prompt, another request come in
DBUS_GET(promptPath2, coll->Delete());
auto prompt2 = getProxy<PromptProxy>(promptPath);
auto prompt2 = getProxy<PromptProxy>(promptPath2);
VERIFY(prompt2);
QSignalSpy spyPromptCompleted2(prompt2.data(), SIGNAL(Completed(bool, QDBusVariant)));
VERIFY(spyPromptCompleted2.isValid());
@@ -1015,6 +1093,7 @@ void TestGuiFdoSecrets::testCollectionDeleteConcurrent()
// there should be no prompt
DBUS_VERIFY(prompt2->Prompt(""));
// the first prompt completes the deletion
VERIFY(waitForSignal(spyPromptCompleted, 1));
{
auto args = spyPromptCompleted.takeFirst();
@@ -1023,11 +1102,13 @@ void TestGuiFdoSecrets::testCollectionDeleteConcurrent()
COMPARE(args.at(1).value<QDBusVariant>().variant().toString(), QStringLiteral(""));
}
// the second prompt fails fast as the deletion is still in progress,
// and is reported as dismissed
VERIFY(waitForSignal(spyPromptCompleted2, 1));
{
auto args = spyPromptCompleted2.takeFirst();
COMPARE(args.count(), 2);
COMPARE(args.at(0).toBool(), false);
COMPARE(args.at(0).toBool(), true);
COMPARE(args.at(1).value<QDBusVariant>().variant().toString(), QStringLiteral(""));
}
+1
View File
@@ -72,6 +72,7 @@ private slots:
void testServiceSearchForce();
void testServiceUnlock();
void testServiceUnlockDatabaseConcurrent();
void testServiceUnlockConcurrentDelete();
void testServiceUnlockItems();
void testServiceUnlockItemsIncludeFutureEntries();
void testServiceLock();