diff --git a/CMakeLists.txt b/CMakeLists.txt index 0afb3d8..a646eba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,54 +1,55 @@ cmake_minimum_required(VERSION 3.5) set(KF5_VERSION "5.71.0") # handled by release scripts set(KF5_DEP_VERSION "5.70.0") # handled by release scripts project(KWallet VERSION ${KF5_VERSION}) set(CMAKE_EXPORT_COMPILE_COMMANDS 1) include(FeatureSummary) find_package(ECM 5.70.0 NO_MODULE) set_package_properties(ECM PROPERTIES TYPE REQUIRED DESCRIPTION "Extra CMake Modules." URL "https://commits.kde.org/extra-cmake-modules") feature_summary(WHAT REQUIRED_PACKAGES_NOT_FOUND FATAL_ON_MISSING_REQUIRED_PACKAGES) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) set(REQUIRED_QT_VERSION 5.12.0) find_package(Qt5 ${REQUIRED_QT_VERSION} CONFIG REQUIRED Widgets DBus) include(KDEInstallDirs) include(KDEFrameworkCompilerSettings NO_POLICY_SCOPE) include(KDECMakeSettings) include(ECMAddQch) +include(ECMGenerateExportHeader) include(ECMSetupVersion) include(ECMQtDeclareLoggingCategory) option(BUILD_KWALLETD "Build the kwallet daemon" ON) option(BUILD_KWALLET_QUERY "Build kwallet-query tool" ON) option(BUILD_QCH "Build API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)" OFF) add_feature_info(QCH ${BUILD_QCH} "API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)") find_package(KF5CoreAddons ${KF5_DEP_VERSION} REQUIRED) find_package(KF5Config ${KF5_DEP_VERSION} REQUIRED) find_package(KF5WindowSystem ${KF5_DEP_VERSION} REQUIRED) find_package(KF5I18n ${KF5_DEP_VERSION} REQUIRED) find_package(KF5DocTools ${KF5_DEP_VERSION}) add_definitions(-DQT_DISABLE_DEPRECATED_BEFORE=0x050d00) add_definitions(-DKF_DISABLE_DEPRECATED_BEFORE_AND_AT=0x054700) add_definitions(-DQT_NO_FOREACH) add_definitions(-DTRANSLATION_DOMAIN=\"kwalletd5\") if (IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/po") ki18n_install(po) endif() add_subdirectory(src) if (BUILD_TESTING) add_subdirectory(autotests) add_subdirectory(tests) add_subdirectory(examples) endif() if (KF5DocTools_FOUND) add_subdirectory(docs) endif() feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/src/api/KWallet/CMakeLists.txt b/src/api/KWallet/CMakeLists.txt index 38a8e56..7e639fb 100644 --- a/src/api/KWallet/CMakeLists.txt +++ b/src/api/KWallet/CMakeLists.txt @@ -1,145 +1,153 @@ include(GenerateExportHeader) include(ECMGenerateHeaders) ecm_setup_version(${KF5_VERSION} VARIABLE_PREFIX KWALLET VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/kwallet_version.h" PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KF5WalletConfigVersion.cmake" SOVERSION 5) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/kwallet_version.h DESTINATION ${KF5_INCLUDE_INSTALL_DIR} COMPONENT Devel ) set(HAVE_KSECRETSSERVICE 0) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config-kwallet.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-kwallet.h ) if(APPLE) option(MAC_USE_OSXKEYCHAIN "On OS X, use the keychain as backend for kwallet, instead of kwalletd.") else() set(MAC_USE_OSXKEYCHAIN FALSE) endif() if (MAC_USE_OSXKEYCHAIN) FIND_LIBRARY(SECURITY_LIBRARY Security) set(kwallet_SRCS kwallet_mac.cpp) else() set(kwallet_SRCS kwallet.cpp) set(kwallet_xml org.kde.KWallet.xml) qt5_add_dbus_interface( kwallet_SRCS ${kwallet_xml} kwallet_interface ) endif() ecm_qt_declare_logging_category(kwallet_SRCS HEADER kwallet_api_debug.h IDENTIFIER KWALLET_API_LOG CATEGORY_NAME kf5.kwallet.api DESCRIPTION "kwallet api" EXPORT KWALLET ) add_library(KF5Wallet ${kwallet_SRCS}) -generate_export_header(KF5Wallet BASE_NAME KWallet) +ecm_generate_export_header(KF5Wallet + BASE_NAME KWallet + GROUP_BASE_NAME KF + VERSION ${KF5_VERSION} + DEPRECATED_BASE_VERSION 0 + DEPRECATION_VERSIONS 5.70 + EXCLUDE_DEPRECATED_BEFORE_AND_AT ${EXCLUDE_DEPRECATED_BEFORE_AND_AT} +) + add_library(KF5::Wallet ALIAS KF5Wallet) target_include_directories(KF5Wallet INTERFACE "$") target_link_libraries(KF5Wallet PUBLIC Qt5::Gui PRIVATE Qt5::DBus Qt5::Widgets PRIVATE KF5::WindowSystem # KWindowSystem::allowExternalProcessWindowActivation KF5::ConfigCore # used to store the wallet to be used ) if(MAC_USE_OSXKEYCHAIN) target_link_libraries(KF5Wallet PRIVATE ${CARBON_LIBRARY} ${SECURITY_LIBRARY}) elseif(APPLE) target_link_libraries(KF5Wallet PRIVATE ${CARBON_LIBRARY}) else() target_link_libraries(KF5Wallet PRIVATE Qt5::DBus) install(FILES ${kwallet_xml} DESTINATION ${KDE_INSTALL_DBUSINTERFACEDIR} RENAME kf5_org.kde.KWallet.xml) endif() set_target_properties(KF5Wallet PROPERTIES VERSION ${KWALLET_VERSION_STRING} SOVERSION ${KWALLET_SOVERSION} EXPORT_NAME Wallet ) ecm_generate_headers(KWallet_HEADERS HEADER_NAMES KWallet REQUIRED_HEADERS KWallet_HEADERS ) install(TARGETS KF5Wallet EXPORT KF5WalletTargets ${KF5_INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/kwallet_export.h ${KWallet_HEADERS} DESTINATION ${KF5_INCLUDE_INSTALL_DIR}/KWallet COMPONENT Devel ) if(BUILD_QCH) ecm_add_qch( KF5Wallet_QCH NAME KWallet BASE_NAME KF5Wallet VERSION ${KF5_VERSION} ORG_DOMAIN org.kde SOURCES # using only public headers, to cover only public API ${KWallet_HEADERS} LINK_QCHS Qt5Gui_QCH INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR} BLANK_MACROS KWALLET_EXPORT KWALLET_DEPRECATED KWALLET_DEPRECATED_EXPORT TAGFILE_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} QCH_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} COMPONENT Devel ) endif() # create a Config.cmake and a ConfigVersion.cmake file and install them set(CMAKECONFIG_INSTALL_DIR "${CMAKECONFIG_INSTALL_PREFIX}/KF5Wallet") if (BUILD_QCH) ecm_install_qch_export( TARGETS KF5Wallet_QCH FILE KF5WalletQchTargets.cmake DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) set(PACKAGE_INCLUDE_QCHTARGETS "include(\"\${CMAKE_CURRENT_LIST_DIR}/KF5WalletQchTargets.cmake\")") endif() include(CMakePackageConfigHelpers) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/KF5WalletConfig.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/KF5WalletConfig.cmake" PATH_VARS KDE_INSTALL_DBUSINTERFACEDIR PATH_VARS KDE_INSTALL_BINDIR INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR} ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/KF5WalletConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/KF5WalletConfigVersion.cmake" DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) install(EXPORT KF5WalletTargets DESTINATION "${CMAKECONFIG_INSTALL_DIR}" FILE KF5WalletTargets.cmake NAMESPACE KF5:: ) include(ECMGeneratePriFile) ecm_generate_pri_file(BASE_NAME KWallet LIB_NAME KF5Wallet DEPS "widgets" FILENAME_VAR PRI_FILENAME INCLUDE_INSTALL_DIR ${KF5_INCLUDE_INSTALL_DIR}/KWallet) install(FILES ${PRI_FILENAME} DESTINATION ${ECM_MKSPECS_INSTALL_DIR}) diff --git a/src/api/KWallet/kwallet.cpp b/src/api/KWallet/kwallet.cpp index f610fc3..cc1f6f6 100644 --- a/src/api/KWallet/kwallet.cpp +++ b/src/api/KWallet/kwallet.cpp @@ -1,1679 +1,1811 @@ /* This file is part of the KDE project * * Copyright (C) 2002-2004 George Staikos * Copyright (C) 2008 Michael Leupold * Copyright (C) 2011 Valentin Rusu * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kwallet.h" #include #include "kwallet_api_debug.h" #include #include #include #include #include #include #if HAVE_KSECRETSSERVICE #include "ksecretsservice/ksecretsservicecollection.h" #endif #include "kwallet_interface.h" #if HAVE_KSECRETSSERVICE typedef QMap StringToStringStringMapMap; Q_DECLARE_METATYPE(StringToStringStringMapMap) #endif typedef QMap StringByteArrayMap; Q_DECLARE_METATYPE(StringByteArrayMap) namespace KWallet { class KWalletDLauncher { public: KWalletDLauncher(); ~KWalletDLauncher(); KWalletDLauncher(const KWalletDLauncher &) = delete; KWalletDLauncher& operator=(const KWalletDLauncher &) = delete; org::kde::KWallet &getInterface(); // this static variable is used below to switch between old KWallet // infrastructure and the new one which is built on top of the new // KSecretsService infrastructure. It's value can be changed via the // the Wallet configuration module in System Settings bool m_useKSecretsService; org::kde::KWallet *m_wallet_deamon; KConfigGroup m_cgroup; bool m_walletEnabled; }; Q_GLOBAL_STATIC(KWalletDLauncher, walletLauncher) static QString appid() { return qApp->applicationName(); } static void registerTypes() { static bool registered = false; if (!registered) { #if HAVE_KSECRETSSERVICE qDBusRegisterMetaType(); qDBusRegisterMetaType(); #endif qDBusRegisterMetaType(); registered = true; } } bool Wallet::isUsingKSecretsService() { return walletLauncher()->m_useKSecretsService; } const QString Wallet::LocalWallet() { // NOTE: This method stays unchanged for KSecretsService KConfigGroup cfg(KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Wallet")); if (!cfg.readEntry("Use One Wallet", true)) { QString tmp = cfg.readEntry("Local Wallet", "localwallet"); if (tmp.isEmpty()) { return QStringLiteral("localwallet"); } return tmp; } QString tmp = cfg.readEntry("Default Wallet", "kdewallet"); if (tmp.isEmpty()) { return QStringLiteral("kdewallet"); } return tmp; } const QString Wallet::NetworkWallet() { // NOTE: This method stays unchanged for KSecretsService KConfigGroup cfg(KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Wallet")); QString tmp = cfg.readEntry("Default Wallet", "kdewallet"); if (tmp.isEmpty()) { return QStringLiteral("kdewallet"); } return tmp; } const QString Wallet::PasswordFolder() { return QStringLiteral("Passwords"); } const QString Wallet::FormDataFolder() { return QStringLiteral("Form Data"); } class Q_DECL_HIDDEN Wallet::WalletPrivate { public: WalletPrivate(Wallet *wallet, int h, const QString &n) : q(wallet), name(n), handle(h) #if HAVE_KSECRETSSERVICE , secretsCollection(0) #endif {} void walletServiceUnregistered(); #if HAVE_KSECRETSSERVICE template int writeEntry(const QString &key, const T &value, Wallet::EntryType entryType) { int rc = -1; KSecretsService::Secret secret; secret.setValue(QVariant::fromValue(value)); KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = folder; attrs[KSS_ATTR_WALLETTYPE] = QString("%1").arg((int)entryType); KSecretsService::CreateCollectionItemJob *createItemJob = secretsCollection->createItem(key, attrs, secret); if (!createItemJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute CreateCollectionItemJob : " << createItemJob->errorString(); } rc = createItemJob->error(); return rc; } QExplicitlySharedDataPointer findItem(const QString &key) const; template int readEntry(const QString &key, T &value) const; bool readSecret(const QString &key, KSecretsService::Secret &value) const; +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) template int forEachItemThatMatches(const QString &key, V verb) { int rc = -1; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = folder; KSecretsService::SearchCollectionItemsJob *searchItemsJob = secretsCollection->searchItems(attrs); if (searchItemsJob->exec()) { // HACK: QRegularExpression::wildcardToRegularExpression() mainly handles file pattern // globbing (e.g. "*.txt") which means it doesn't allow "/" in the file name (which is // technically correct); we have to subvert it because the keys in kwallet are in the // form e.g. "foo.com/" which does have a "/" in it const QString pattern = QRegularExpression::wildcardToRegularExpression(key).replace( QLatin1String("[^/]"), QLatin1String(".")); const QRegularExpression re(pattern); const auto list = searchItemsJob->items(); for (KSecretsService::SearchCollectionItemsJob::Item item : list) { KSecretsService::ReadItemPropertyJob *readLabelJob = item->label(); if (readLabelJob->exec()) { QString label = readLabelJob->propertyValue().toString(); if (re.match(label).hasMatch()) { if (verb(this, label, item.data())) { rc = 0; // one successful iteration already produced results, so success return } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute ReadItemPropertyJob " << readLabelJob->errorString(); } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute KSecretsService::SearchCollectionItemsJob " << searchItemsJob->errorString(); } return rc; } +#endif + + template int checkItems(V verb) + { + int rc = -1; + KSecretsService::StringStringMap attrs; + attrs[KSS_ATTR_ENTRYFOLDER] = folder; + KSecretsService::SearchCollectionItemsJob *searchItemsJob = secretsCollection->searchItems(attrs); + if (searchItemsJob->exec()) { + const auto list = searchItemsJob->items(); + for (KSecretsService::SearchCollectionItemsJob::Item item : list) { + KSecretsService::ReadItemPropertyJob *readLabelJob = item->label(); + if (readLabelJob->exec()) { + const QString label = readLabelJob->propertyValue().toString(); + if (verb(this, label, item.data())) { + rc = 0; // one successful iteration already produced results, so success return + } + } else { + qCDebug(KWALLET_API_LOG) << "Cannot execute ReadItemPropertyJob " << readLabelJob->errorString(); + } + } + } else { + qCDebug(KWALLET_API_LOG) << "Cannot execute KSecretsService::SearchCollectionItemsJob " << searchItemsJob->errorString(); + } + return rc; + } void createDefaultFolders(); struct InsertIntoEntryList; struct InsertIntoMapList; struct InsertIntoPasswordList; KSecretsService::Collection *secretsCollection; #endif // HAVE_KSECRETSSERVICE Wallet *q; QString name; QString folder; int handle; int transactionId; }; #if HAVE_KSECRETSSERVICE void Wallet::WalletPrivate::createDefaultFolders() { // NOTE: KWalletManager expects newly created wallets to have two default folders // b->createFolder(KWallet::Wallet::PasswordFolder()); // b->createFolder(KWallet::Wallet::FormDataFolder()); QString strDummy(""); folder = PasswordFolder(); writeEntry(PasswordFolder(), strDummy, KWallet::Wallet::Unknown); folder = FormDataFolder(); writeEntry(FormDataFolder(), strDummy, KWallet::Wallet::Unknown); } #endif // HAVE_KSECRETSSERVICE static const char s_kwalletdServiceName[] = "org.kde.kwalletd5"; Wallet::Wallet(int handle, const QString &name) : QObject(nullptr), d(new WalletPrivate(this, handle, name)) { if (walletLauncher()->m_useKSecretsService) { // see openWallet for initialization code; this constructor does not have any code } else { QDBusServiceWatcher *watcher = new QDBusServiceWatcher(QString::fromLatin1(s_kwalletdServiceName), QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this); connect(watcher, SIGNAL(serviceUnregistered(QString)), this, SLOT(walletServiceUnregistered())); connect(&walletLauncher()->getInterface(), SIGNAL(walletClosed(int)), SLOT(slotWalletClosed(int))); connect(&walletLauncher()->getInterface(), SIGNAL(folderListUpdated(QString)), SLOT(slotFolderListUpdated(QString))); connect(&walletLauncher()->getInterface(), SIGNAL(folderUpdated(QString,QString)), SLOT(slotFolderUpdated(QString,QString))); connect(&walletLauncher()->getInterface(), SIGNAL(applicationDisconnected(QString,QString)), SLOT(slotApplicationDisconnected(QString,QString))); // Verify that the wallet is still open if (d->handle != -1) { QDBusReply r = walletLauncher()->getInterface().isOpen(d->handle); if (r.isValid() && !r) { d->handle = -1; d->name.clear(); } } } } Wallet::~Wallet() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { d->folder.clear(); d->name.clear(); delete d->secretsCollection; } else { #endif if (d->handle != -1) { if (!walletLauncher.isDestroyed()) { walletLauncher()->getInterface().close(d->handle, false, appid()); } else { qCDebug(KWALLET_API_LOG) << "Problem with static destruction sequence." "Destroy any static Wallet before the event-loop exits."; } d->handle = -1; d->folder.clear(); d->name.clear(); } #if HAVE_KSECRETSSERVICE } #endif delete d; } QStringList Wallet::walletList() { QStringList result; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::ListCollectionsJob *listJob = KSecretsService::Collection::listCollections(); if (listJob->exec()) { result = listJob->collections(); } else { qCDebug(KWALLET_API_LOG) << "Cannot execute ListCollectionsJob: " << listJob->errorString(); } } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().wallets(); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); } else { result = r; } } #if HAVE_KSECRETSSERVICE } #endif return result; } void Wallet::changePassword(const QString &name, WId w) { if (w == 0) { qCDebug(KWALLET_API_LOG) << "Pass a valid window to KWallet::Wallet::changePassword()."; } // Make sure the password prompt window will be visible and activated KWindowSystem::allowExternalProcessWindowActivation(); #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::Collection *coll = KSecretsService::Collection::findCollection(name); KSecretsService::ChangeCollectionPasswordJob *changePwdJob = coll->changePassword(); if (!changePwdJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute change password job: " << changePwdJob->errorString(); } coll->deleteLater(); } else { #endif if (walletLauncher()->m_walletEnabled) { walletLauncher()->getInterface().changePassword(name, (qlonglong)w, appid()); } #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::isEnabled() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { return walletLauncher()->m_cgroup.readEntry("Enabled", true); } else { #endif return walletLauncher()->m_walletEnabled; #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::isOpen(const QString &name) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::Collection *coll = KSecretsService::Collection::findCollection(name, KSecretsService::Collection::OpenOnly); KSecretsService::ReadCollectionPropertyJob *readLocked = coll->isLocked(); if (readLocked->exec()) { return !readLocked->propertyValue().toBool(); } else { qCDebug(KWALLET_API_LOG) << "ReadLocked job failed"; return false; } } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().isOpen(name); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return false; #if HAVE_KSECRETSSERVICE } #endif } int Wallet::closeWallet(const QString &name, bool force) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "Wallet::closeWallet NOOP"; return 0; } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().close(name, force); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return -1; } else { return r; } } else return -1; #if HAVE_KSECRETSSERVICE } #endif } int Wallet::deleteWallet(const QString &name) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::Collection *coll = KSecretsService::Collection::findCollection(name, KSecretsService::Collection::OpenOnly); KJob *deleteJob = coll->deleteCollection(); if (!deleteJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute delete job " << deleteJob->errorString(); } return deleteJob->error(); } else { #endif if (walletLauncher->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().deleteWallet(name); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return -1; } else { return r; } } else return -1; #if HAVE_KSECRETSSERVICE } #endif } Wallet *Wallet::openWallet(const QString &name, WId w, OpenType ot) { if (w == 0) { qCDebug(KWALLET_API_LOG) << "Pass a valid window to KWallet::Wallet::openWallet()."; } if (!walletLauncher()->m_walletEnabled) { qCDebug(KWALLET_API_LOG) << "User disabled the wallet system so returning 0 here."; return nullptr; } #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { Wallet *wallet = new Wallet(-1, name); // FIXME: should we specify CreateCollection or OpenOnly here? wallet->d->secretsCollection = KSecretsService::Collection::findCollection(name, KSecretsService::Collection::CreateCollection, QVariantMap(), w); connect(wallet->d->secretsCollection, SIGNAL(statusChanged(int)), wallet, SLOT(slotCollectionStatusChanged(int))); connect(wallet->d->secretsCollection, SIGNAL(deleted()), wallet, SLOT(slotCollectionDeleted())); if (ot == Synchronous) { qCDebug(KWALLET_API_LOG) << "WARNING openWallet OpenType=Synchronous requested"; // TODO: not sure what to do with in this case; however, all other KSecretsService API methods are already // async and will perform sync inside this API because of it's design } return wallet; } else { #endif Wallet *wallet = new Wallet(-1, name); // connect the daemon's opened signal to the slot filtering the // signals we need connect(&walletLauncher()->getInterface(), SIGNAL(walletAsyncOpened(int,int)), wallet, SLOT(walletAsyncOpened(int,int))); // Make sure the password prompt window will be visible and activated KWindowSystem::allowExternalProcessWindowActivation(); org::kde::KWallet &interface = walletLauncher->getInterface(); // do the call QDBusReply r; if (ot == Synchronous) { interface.setTimeout(0x7FFFFFFF); // Don't timeout after 25s, but 24 days r = interface.open(name, (qlonglong)w, appid()); interface.setTimeout(-1); // Back to the default 25s // after this call, r would contain a transaction id >0 if OK or -1 if NOK // if OK, the slot walletAsyncOpened should have been received, but the transaction id // will not match. We'll get that handle from the reply - see below } else if (ot == Asynchronous) { r = interface.openAsync(name, (qlonglong)w, appid(), true); } else if (ot == Path) { r = interface.openPathAsync(name, (qlonglong)w, appid(), true); } else { delete wallet; return nullptr; } // error communicating with the daemon (maybe not running) if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); delete wallet; return nullptr; } wallet->d->transactionId = r.value(); if (ot == Synchronous || ot == Path) { // check for an immediate error if (wallet->d->transactionId < 0) { delete wallet; wallet = nullptr; } else { wallet->d->handle = r.value(); } } else if (ot == Asynchronous) { if (wallet->d->transactionId < 0) { QTimer::singleShot(0, wallet, SLOT(emitWalletAsyncOpenError())); // client code is responsible for deleting the wallet } } return wallet; #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotCollectionStatusChanged(int status) { #if HAVE_KSECRETSSERVICE KSecretsService::Collection::Status collStatus = (KSecretsService::Collection::Status)status; switch (collStatus) { case KSecretsService::Collection::NewlyCreated: d->createDefaultFolders(); // fall through case KSecretsService::Collection::FoundExisting: emitWalletOpened(); break; case KSecretsService::Collection::Deleted: case KSecretsService::Collection::Invalid: case KSecretsService::Collection::Pending: // nothing to do break; case KSecretsService::Collection::NotFound: emitWalletAsyncOpenError(); break; } #else Q_UNUSED(status) #endif } void Wallet::slotCollectionDeleted() { d->folder.clear(); d->name.clear(); emit walletClosed(); } bool Wallet::disconnectApplication(const QString &wallet, const QString &app) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "Wallet::disconnectApplication NOOP"; return true; } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().disconnectApplication(wallet, app); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return -1; #if HAVE_KSECRETSSERVICE } #endif } QStringList Wallet::users(const QString &name) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "KSecretsService does not handle users list"; return QStringList(); } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().users(name); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return QStringList(); } else { return r; } } else return QStringList(); #if HAVE_KSECRETSSERVICE } #endif } int Wallet::sync() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // NOOP with KSecretsService } else { #endif if (d->handle == -1) { return -1; } walletLauncher()->getInterface().sync(d->handle, appid()); #if HAVE_KSECRETSSERVICE } #endif return 0; } int Wallet::lockWallet() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::CollectionLockJob *lockJob = d->secretsCollection->lock(); if (lockJob->exec()) { d->folder.clear(); d->name.clear(); } else { qCDebug(KWALLET_API_LOG) << "Cannot execute KSecretsService::CollectionLockJob : " << lockJob->errorString(); return -1; } return lockJob->error(); } else { #endif if (d->handle == -1) { return -1; } QDBusReply r = walletLauncher()->getInterface().close(d->handle, true, appid()); d->handle = -1; d->folder.clear(); d->name.clear(); if (r.isValid()) { return r; } else { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return -1; } #if HAVE_KSECRETSSERVICE } #endif } const QString &Wallet::walletName() const { return d->name; } bool Wallet::isOpen() const { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { return !d->secretsCollection->isLocked(); } else { #endif return d->handle != -1; #if HAVE_KSECRETSSERVICE } #endif } void Wallet::requestChangePassword(WId w) { if (w == 0) { qCDebug(KWALLET_API_LOG) << "Pass a valid window to KWallet::Wallet::requestChangePassword()."; } #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { KSecretsService::ChangeCollectionPasswordJob *changePwdJob = d->secretsCollection->changePassword(); if (!changePwdJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute ChangeCollectionPasswordJob : " << changePwdJob->errorString(); } } else { #endif if (d->handle == -1) { return; } // Make sure the password prompt window will be visible and activated KWindowSystem::allowExternalProcessWindowActivation(); walletLauncher()->getInterface().changePassword(d->name, (qlonglong)w, appid()); #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotWalletClosed(int handle) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->handle == handle) { d->handle = -1; d->folder.clear(); d->name.clear(); emit walletClosed(); } #if HAVE_KSECRETSSERVICE } #endif } QStringList Wallet::folderList() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QStringList result; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = ""; // search for items having this attribute no matter what value it has KSecretsService::SearchCollectionItemsJob *searchJob = d->secretsCollection->searchItems(attrs); if (searchJob->exec()) { const KSecretsService::ReadCollectionItemsJob::ItemList itemList = searchJob->items(); for (const KSecretsService::ReadCollectionItemsJob::Item &item : itemList) { KSecretsService::ReadItemPropertyJob *readAttrsJob = item->attributes(); if (readAttrsJob->exec()) { KSecretsService::StringStringMap attrs = readAttrsJob->propertyValue().value(); const QString folder = attrs[KSS_ATTR_ENTRYFOLDER]; if (!folder.isEmpty() && !result.contains(folder)) { result.append(folder); } } else { qCDebug(KWALLET_API_LOG) << "Cannot read item attributes : " << readAttrsJob->errorString(); } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute ReadCollectionItemsJob : " << searchJob->errorString(); } return result; } else { #endif if (d->handle == -1) { return QStringList(); } QDBusReply r = walletLauncher()->getInterface().folderList(d->handle, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return QStringList(); } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } QStringList Wallet::entryList() { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QStringList result; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = d->folder; KSecretsService::SearchCollectionItemsJob *readItemsJob = d->secretsCollection->searchItems(attrs); if (readItemsJob->exec()) { const auto list = readItemsJob->items(); for (KSecretsService::SearchCollectionItemsJob::Item item : list) { KSecretsService::ReadItemPropertyJob *readLabelJob = item->label(); if (readLabelJob->exec()) { result.append(readLabelJob->propertyValue().toString()); } else { qCDebug(KWALLET_API_LOG) << "Cannot execute readLabelJob" << readItemsJob->errorString(); } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute readItemsJob" << readItemsJob->errorString(); } return result; } else { #endif if (d->handle == -1) { return QStringList(); } QDBusReply r = walletLauncher()->getInterface().entryList(d->handle, d->folder, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return QStringList(); } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::hasFolder(const QString &f) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // FIXME: well, this is not the best implementation, but it's done quickly :) // the best way would be to searchItems with the attribute label having the value f // doing that would reduce DBus traffic. But KWallet API wille not last. QStringList folders = folderList(); return folders.contains(f); } else { #endif if (d->handle == -1) { return false; } QDBusReply r = walletLauncher()->getInterface().hasFolder(d->handle, f, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::createFolder(const QString &f) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QString strDummy(""); d->folder = f; d->writeEntry(f, strDummy, KWallet::Wallet::Unknown); return true; } else { #endif if (d->handle == -1) { return false; } if (!hasFolder(f)) { QDBusReply r = walletLauncher()->getInterface().createFolder(d->handle, f, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } return true; // folder already exists #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::setFolder(const QString &f) { bool rc = false; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { if (hasFolder(f)) { d->folder = f; rc = true; } } else { #endif if (d->handle == -1) { return rc; } // Don't do this - the folder could have disappeared? #if 0 if (f == d->folder) { return true; } #endif if (hasFolder(f)) { d->folder = f; rc = true; } #if HAVE_KSECRETSSERVICE } #endif return rc; } bool Wallet::removeFolder(const QString &f) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { bool result = false; // search for all items having the folder f then delete them KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = f; KSecretsService::SearchCollectionItemsJob *searchJob = d->secretsCollection->searchItems(attrs); if (searchJob->exec()) { const KSecretsService::SearchCollectionItemsJob::ItemList itemList = searchJob->items(); if (!itemList.isEmpty()) { result = true; for (const KSecretsService::SearchCollectionItemsJob::Item &item : itemList) { KSecretsService::SecretItemDeleteJob *deleteJob = item->deleteItem(); if (!deleteJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot delete item : " << deleteJob->errorString(); result = false; } result &= true; } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute KSecretsService::SearchCollectionItemsJob : " << searchJob->errorString(); } return result; } else { #endif if (d->handle == -1) { return false; } QDBusReply r = walletLauncher()->getInterface().removeFolder(d->handle, f, appid()); if (d->folder == f) { setFolder(QString()); } if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } const QString &Wallet::currentFolder() const { return d->folder; } #if HAVE_KSECRETSSERVICE QExplicitlySharedDataPointer Wallet::WalletPrivate::findItem(const QString &key) const { QExplicitlySharedDataPointer result; KSecretsService::StringStringMap attrs; attrs[KSS_ATTR_ENTRYFOLDER] = folder; attrs["Label"] = key; KSecretsService::SearchCollectionItemsJob *searchJob = secretsCollection->searchItems(attrs); if (searchJob->exec()) { KSecretsService::SearchCollectionItemsJob::ItemList itemList = searchJob->items(); if (!itemList.isEmpty()) { result = itemList.first(); } else { qCDebug(KWALLET_API_LOG) << "entry named " << key << " not found in folder " << folder; } } else { qCDebug(KWALLET_API_LOG) << "Cannot exec KSecretsService::SearchCollectionItemsJob : " << searchJob->errorString(); } return result; } template int Wallet::WalletPrivate::readEntry(const QString &key, T &value) const { int rc = -1; QExplicitlySharedDataPointer item = findItem(key); if (item) { KSecretsService::GetSecretItemSecretJob *readJob = item->getSecret(); if (readJob->exec()) { KSecretsService::Secret theSecret = readJob->secret(); qCDebug(KWALLET_API_LOG) << "Secret contentType is " << theSecret.contentType(); value = theSecret.value().value(); rc = 0; } else { qCDebug(KWALLET_API_LOG) << "Cannot exec GetSecretItemSecretJob : " << readJob->errorString(); } } return rc; } bool Wallet::WalletPrivate::readSecret(const QString &key, KSecretsService::Secret &value) const { bool result = false; QExplicitlySharedDataPointer item = findItem(key); if (item) { KSecretsService::GetSecretItemSecretJob *readJob = item->getSecret(); if (readJob->exec()) { value = readJob->secret(); result = true; } else { qCDebug(KWALLET_API_LOG) << "Cannot exec GetSecretItemSecretJob : " << readJob->errorString(); } } return result; } #endif int Wallet::readEntry(const QString &key, QByteArray &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { return d->readEntry(key, value); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readEntry(d->handle, d->folder, key, appid()); if (r.isValid()) { value = r; rc = 0; } #if HAVE_KSECRETSSERVICE } #endif return rc; } #if HAVE_KSECRETSSERVICE struct Wallet::WalletPrivate::InsertIntoEntryList { InsertIntoEntryList(QMap< QString, QByteArray> &value) : _value(value) {} bool operator()(Wallet::WalletPrivate *, const QString &label, KSecretsService::SecretItem *item) { bool result = false; KSecretsService::GetSecretItemSecretJob *readSecretJob = item->getSecret(); if (readSecretJob->exec()) { _value.insert(label, readSecretJob->secret().value().toByteArray()); result = true; } else { qCDebug(KWALLET_API_LOG) << "Cannot execute GetSecretItemSecretJob " << readSecretJob->errorString(); } return result; } QMap< QString, QByteArray > _value; }; #endif +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) int Wallet::readEntryList(const QString &key, QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->forEachItemThatMatches(key, WalletPrivate::InsertIntoEntryList(value)); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readEntryList(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; // convert to const QVariantMap val = r.value(); for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { value.insert(it.key(), it.value().toByteArray()); } } #if HAVE_KSECRETSSERVICE } #endif return rc; } +#endif + +int Wallet::entriesList(QMap &value) +{ + + int rc = -1; + +#if HAVE_KSECRETSSERVICE + if (walletLauncher()->m_useKSecretsService) { + rc = d->checkItems(WalletPrivate::InsertIntoEntryList(value)); + } else { +#endif + registerTypes(); + + if (d->handle == -1) { + return rc; + } + + QDBusReply reply = walletLauncher()->getInterface().entriesList(d->handle, d->folder, appid()); + if (reply.isValid()) { + rc = 0; + // convert to + const QVariantMap val = reply.value(); + for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { + value.insert(it.key(), it.value().toByteArray()); + } + } +#if HAVE_KSECRETSSERVICE + } +#endif + + return rc; +} + int Wallet::renameEntry(const QString &oldName, const QString &newName) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(oldName); if (item) { KSecretsService::WriteItemPropertyJob *writeJob = item->setLabel(newName); if (!writeJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot exec WriteItemPropertyJob : " << writeJob->errorString(); } rc = writeJob->error(); } else { qCDebug(KWALLET_API_LOG) << "Cannot locate item " << oldName << " in folder " << d->folder; } } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().renameEntry(d->handle, d->folder, oldName, newName, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::readMap(const QString &key, QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QByteArray ba; rc = d->readEntry< QByteArray >(key, ba); if (rc == 0 && !ba.isEmpty()) { QDataStream ds(&ba, QIODevice::ReadOnly); ds >> value; } } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readMap(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; QByteArray v = r; if (!v.isEmpty()) { QDataStream ds(&v, QIODevice::ReadOnly); ds >> value; } } #if HAVE_KSECRETSSERVICE } #endif return rc; } #if HAVE_KSECRETSSERVICE struct Wallet::WalletPrivate::InsertIntoMapList { InsertIntoMapList(QMap< QString, QMap< QString, QString > > &value) : _value(value) {} bool operator()(Wallet::WalletPrivate *d, const QString &label, KSecretsService::SecretItem *) { bool result = false; QMap map; if (d->readEntry< QMap< QString, QString> >(label, map)) { _value.insert(label, map); result = true; } return result; } QMap< QString, QMap< QString, QString> > &_value; }; #endif +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) int Wallet::readMapList(const QString &key, QMap > &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->forEachItemThatMatches(key, WalletPrivate::InsertIntoMapList(value)); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readMapList(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; const QVariantMap val = r.value(); for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { QByteArray mapData = it.value().toByteArray(); if (!mapData.isEmpty()) { QDataStream ds(&mapData, QIODevice::ReadOnly); QMap v; ds >> v; value.insert(it.key(), v); } } } #if HAVE_KSECRETSSERVICE } #endif return rc; } +#endif + +int Wallet::mapList(QMap > &value) +{ + int rc = -1; + +#if HAVE_KSECRETSSERVICE + if (walletLauncher()->m_useKSecretsService) { + rc = d->checkItems(WalletPrivate::InsertIntoMapList(value)); + } else { +#endif + registerTypes(); + + if (d->handle == -1) { + return rc; + } + + QDBusReply reply = walletLauncher()->getInterface().mapList(d->handle, d->folder, appid()); + if (reply.isValid()) { + rc = 0; + const QVariantMap val = reply.value(); + for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { + QByteArray mapData = it.value().toByteArray(); + if (!mapData.isEmpty()) { + QDataStream ds(&mapData, QIODevice::ReadOnly); + QMap v; + ds >> v; + value.insert(it.key(), v); + } + } + } +#if HAVE_KSECRETSSERVICE + } +#endif + + return rc; +} int Wallet::readPassword(const QString &key, QString &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->readEntry(key, value); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readPassword(d->handle, d->folder, key, appid()); if (r.isValid()) { value = r; rc = 0; } #if HAVE_KSECRETSSERVICE } #endif return rc; } #if HAVE_KSECRETSSERVICE struct Wallet::WalletPrivate::InsertIntoPasswordList { InsertIntoPasswordList(QMap< QString, QString> &value) : _value(value) {} bool operator()(Wallet::WalletPrivate *d, const QString &label, KSecretsService::SecretItem *) { bool result = false; QString pwd; if (d->readEntry(label, pwd) == 0) { _value.insert(label, pwd); result = true; } return result; } QMap< QString, QString > &_value; }; #endif +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) int Wallet::readPasswordList(const QString &key, QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->forEachItemThatMatches(key, WalletPrivate::InsertIntoPasswordList(value)); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().readPasswordList(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = 0; const QVariantMap val = r.value(); for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { value.insert(it.key(), it.value().toString()); } } #if HAVE_KSECRETSSERVICE } #endif return rc; } +#endif + +int Wallet::passwordList(QMap &value) +{ + int rc = -1; + +#if HAVE_KSECRETSSERVICE + if (walletLauncher()->m_useKSecretsService) { + rc = d->checkItems(WalletPrivate::InsertIntoPasswordList(value)); + } else { +#endif + registerTypes(); + + if (d->handle == -1) { + return rc; + } + + QDBusReply reply = walletLauncher()->getInterface().passwordList(d->handle, d->folder, appid()); + if (reply.isValid()) { + rc = 0; + const QVariantMap val = reply.value(); + for (QVariantMap::const_iterator it = val.begin(); it != val.end(); ++it) { + value.insert(it.key(), it.value().toString()); + } + } +#if HAVE_KSECRETSSERVICE + } +#endif + + return rc; +} int Wallet::writeEntry(const QString &key, const QByteArray &value, EntryType entryType) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->writeEntry(key, value, entryType); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().writeEntry(d->handle, d->folder, key, value, int(entryType), appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::writeEntry(const QString &key, const QByteArray &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = writeEntry(key, value, Stream); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().writeEntry(d->handle, d->folder, key, value, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::writeMap(const QString &key, const QMap &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { d->writeEntry(key, value, Map); } else { #endif registerTypes(); if (d->handle == -1) { return rc; } QByteArray mapData; QDataStream ds(&mapData, QIODevice::WriteOnly); ds << value; QDBusReply r = walletLauncher()->getInterface().writeMap(d->handle, d->folder, key, mapData, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } int Wallet::writePassword(const QString &key, const QString &value) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { rc = d->writeEntry(key, value, Password); } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().writePassword(d->handle, d->folder, key, value, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } bool Wallet::hasEntry(const QString &key) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(key); return item; } else { #endif if (d->handle == -1) { return false; } QDBusReply r = walletLauncher()->getInterface().hasEntry(d->handle, d->folder, key, appid()); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } #if HAVE_KSECRETSSERVICE } #endif } int Wallet::removeEntry(const QString &key) { int rc = -1; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(key); if (item) { KSecretsService::SecretItemDeleteJob *deleteJob = item->deleteItem(); if (!deleteJob->exec()) { qCDebug(KWALLET_API_LOG) << "Cannot execute SecretItemDeleteJob " << deleteJob->errorString(); } rc = deleteJob->error(); } } else { #endif if (d->handle == -1) { return rc; } QDBusReply r = walletLauncher()->getInterface().removeEntry(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return rc; } Wallet::EntryType Wallet::entryType(const QString &key) { int rc = 0; #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { QExplicitlySharedDataPointer item = d->findItem(key); if (item) { KSecretsService::ReadItemPropertyJob *readAttrsJob = item->attributes(); if (readAttrsJob->exec()) { KSecretsService::StringStringMap attrs = readAttrsJob->propertyValue().value(); if (attrs.contains(KSS_ATTR_WALLETTYPE)) { QString entryType = attrs[KSS_ATTR_WALLETTYPE]; bool ok = false; rc = entryType.toInt(&ok); if (!ok) { rc = 0; qCDebug(KWALLET_API_LOG) << KSS_ATTR_WALLETTYPE << " attribute holds non int value " << attrs[KSS_ATTR_WALLETTYPE]; } } } else { qCDebug(KWALLET_API_LOG) << "Cannot execute GetSecretItemSecretJob " << readAttrsJob->errorString(); } } } else { #endif if (d->handle == -1) { return Wallet::Unknown; } QDBusReply r = walletLauncher()->getInterface().entryType(d->handle, d->folder, key, appid()); if (r.isValid()) { rc = r; } #if HAVE_KSECRETSSERVICE } #endif return static_cast(rc); } void Wallet::WalletPrivate::walletServiceUnregistered() { if (handle >= 0) { q->slotWalletClosed(handle); } } void Wallet::slotFolderUpdated(const QString &wallet, const QString &folder) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->name == wallet) { emit folderUpdated(folder); } #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotFolderListUpdated(const QString &wallet) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->name == wallet) { emit folderListUpdated(); } #if HAVE_KSECRETSSERVICE } #endif } void Wallet::slotApplicationDisconnected(const QString &wallet, const QString &application) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif if (d->handle >= 0 && d->name == wallet && application == appid()) { slotWalletClosed(d->handle); } #if HAVE_KSECRETSSERVICE } #endif } void Wallet::walletAsyncOpened(int tId, int handle) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { // TODO: implement this Q_ASSERT(0); } else { #endif // ignore responses to calls other than ours if (d->transactionId != tId || d->handle != -1) { return; } // disconnect the async signal disconnect(this, SLOT(walletAsyncOpened(int,int))); d->handle = handle; emit walletOpened(handle > 0); #if HAVE_KSECRETSSERVICE } #endif } void Wallet::emitWalletAsyncOpenError() { emit walletOpened(false); } void Wallet::emitWalletOpened() { emit walletOpened(true); } bool Wallet::folderDoesNotExist(const QString &wallet, const QString &folder) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "WARNING: changing semantics of folderDoesNotExist with KSS: will prompt for the password"; Wallet *w = openWallet(wallet, 0, Synchronous); if (w) { return !w->hasFolder(folder); } else { return true; } } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().folderDoesNotExist(wallet, folder); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return false; #if HAVE_KSECRETSSERVICE } #endif } bool Wallet::keyDoesNotExist(const QString &wallet, const QString &folder, const QString &key) { #if HAVE_KSECRETSSERVICE if (walletLauncher()->m_useKSecretsService) { qCDebug(KWALLET_API_LOG) << "WARNING: changing semantics of keyDoesNotExist with KSS: will prompt for the password"; Wallet *w = openWallet(wallet, 0, Synchronous); if (w) { return !w->hasEntry(key); } return false; } else { #endif if (walletLauncher()->m_walletEnabled) { QDBusReply r = walletLauncher()->getInterface().keyDoesNotExist(wallet, folder, key); if (!r.isValid()) { qCDebug(KWALLET_API_LOG) << "Invalid DBus reply: " << r.error(); return false; } else { return r; } } else return false; #if HAVE_KSECRETSSERVICE } #endif } void Wallet::virtual_hook(int, void *) { //BASE::virtual_hook( id, data ); } KWalletDLauncher::KWalletDLauncher() : m_wallet_deamon(nullptr) , m_cgroup(KSharedConfig::openConfig(QStringLiteral("kwalletrc") , KConfig::NoGlobals)->group("Wallet")) , m_walletEnabled(false) { m_useKSecretsService = m_cgroup.readEntry("UseKSecretsService", false); m_walletEnabled = m_cgroup.readEntry("Enabled", true); if (!m_walletEnabled) { qCDebug(KWALLET_API_LOG) << "The wallet service was disabled by the user"; return; } #if HAVE_KSECRETSSERVICE if (m_useKSecretsService) { // NOOP } else { #endif m_wallet_deamon = new org::kde::KWallet(QString::fromLatin1(s_kwalletdServiceName), QStringLiteral("/modules/kwalletd5"), QDBusConnection::sessionBus()); #if HAVE_KSECRETSSERVICE } #endif } KWalletDLauncher::~KWalletDLauncher() { delete m_wallet_deamon; } org::kde::KWallet &KWalletDLauncher::getInterface() { // Q_ASSERT(!m_useKSecretsService); Q_ASSERT(m_wallet_deamon != nullptr); // check if kwalletd is already running QDBusConnectionInterface *bus = QDBusConnection::sessionBus().interface(); if (!bus->isServiceRegistered(QString::fromLatin1(s_kwalletdServiceName))) { // not running! check if it is enabled. if (m_walletEnabled) { // wallet is enabled! try launching it QDBusReply reply = bus->startService(QString::fromLatin1(s_kwalletdServiceName)); if (!reply.isValid()) { qCritical() << "Couldn't start kwalletd: " << reply.error(); } if (!bus->isServiceRegistered(QString::fromLatin1(s_kwalletdServiceName))) { qCDebug(KWALLET_API_LOG) << "The kwalletd service is still not registered"; } else { qCDebug(KWALLET_API_LOG) << "The kwalletd service has been registered"; } } else { qCritical() << "The kwalletd service has been disabled"; } } return *m_wallet_deamon; } } // namespace KWallet #include "moc_kwallet.cpp" diff --git a/src/api/KWallet/kwallet.h b/src/api/KWallet/kwallet.h index 2b56123..df10508 100644 --- a/src/api/KWallet/kwallet.h +++ b/src/api/KWallet/kwallet.h @@ -1,559 +1,605 @@ /* This file is part of the KDE project * * Copyright (C) 2002-2004 George Staikos * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef _KWALLET_H #define _KWALLET_H #include #include #include // krazy:exclude=includes (for WId) #include /** * NOTE: KSecretsService folder semantics * The KWallet API uses folders for organising items. KSecretsService does not * have this notion. But it uses attributes that can be applied arbitrarily on * all the items. The KWallet code that maps to KSecretsService applies an special * attribute KSS_ATTR_ENTRYFOLDER to all items with the currentFolder() value. * The KWallet folder API's calls will always succeed and they'll only change the * current folder value. The folderList() call will scan all the collection * items and collect the KSS_ATTR_ENTRYFOLDER attributes into a list. */ /** * NOTE: KWalet API distinguish KSecretsService collection items by attaching * them some specific attributes, defined below */ #define KSS_ATTR_ENTRYFOLDER "kwallet.folderName" #define KSS_ATTR_WALLETTYPE "kwallet.type" namespace KWallet { /** * KDE Wallet * * This class implements a generic system-wide Wallet for KDE. This is the * ONLY public interface. * * @author George Staikos * @short KDE Wallet Class */ class KWALLET_EXPORT Wallet : public QObject { Q_OBJECT protected: /** * Construct a KWallet object. * @internal * @param handle The handle for the wallet. * @param name The name of the wallet. */ Wallet(int handle, const QString &name); /** * Copy a KWallet object. * @internal */ Wallet(const Wallet &); public: enum EntryType { Unknown = 0, Password, Stream, Map, Unused = 0xffff }; /** * Destroy a KWallet object. Closes the wallet. */ ~Wallet() override; /** * List all the wallets available. * @return Returns a list of the names of all wallets that are * open. */ static QStringList walletList(); /** * Determine if the KDE wallet is enabled. Normally you do * not need to use this because openWallet() will just fail. * @return Returns true if the wallet enabled, else false. */ static bool isEnabled(); /** * Determine if the wallet @p name is open by any application. * @param name The name of the wallet to check. * @return Returns true if the wallet is open, else false. */ static bool isOpen(const QString &name); /** * Close the wallet @p name. The wallet will only be closed * if it is open but not in use (rare), or if it is forced * closed. * @param name The name of the wallet to close. * @param force Set true to force the wallet closed even if it * is in use by others. * @return Returns 0 on success, non-zero on error. */ static int closeWallet(const QString &name, bool force); /** * Delete the wallet @p name. The wallet will be forced closed * first. * @param name The name of the wallet to delete. * @return Returns 0 on success, non-zero on error. */ static int deleteWallet(const QString &name); /** * Disconnect the application @p app from @p wallet. * @param wallet The name of the wallet to disconnect. * @param app The name of the application to disconnect. * @return Returns true on success, false on error. */ static bool disconnectApplication(const QString &wallet, const QString &app); enum OpenType { Synchronous = 0, Asynchronous, Path, OpenTypeUnused = 0xff }; /** * Open the wallet @p name. The user will be prompted to * allow your application to open the wallet, and may be * prompted for a password. You are responsible for deleting * this object when you are done with it. * @param name The name of the wallet to open. * @param ot If Asynchronous, the call will return * immediately with a non-null pointer to an * invalid wallet. You must immediately connect * the walletOpened() signal to a slot so that * you will know when it is opened, or when it * fails. * @param w The window id to associate any dialogs with. You can pass * 0 if you don't have a window the password dialog should * associate with. * @return Returns a pointer to the wallet if successful, * or a null pointer on error or if rejected. * A null pointer can also be returned if user choose to * deactivate the wallet system. */ static Wallet *openWallet(const QString &name, WId w, OpenType ot = Synchronous); /** * List the applications that are using the wallet @p wallet. * @param wallet The wallet to query. * @return Returns a list of all DCOP application IDs using * the wallet. */ static QStringList users(const QString &wallet); /** * The name of the wallet used to store local passwords. */ static const QString LocalWallet(); /** * The name of the wallet used to store network passwords. */ static const QString NetworkWallet(); /** * The standardized name of the password folder. * It is automatically created when a wallet is created, but * the user may still delete it so you should check for its * existence and recreate it if necessary and desired. */ static const QString PasswordFolder(); /** * The standardized name of the form data folder. * It is automatically created when a wallet is created, but * the user may still delete it so you should check for its * existence and recreate it if necessary and desired. */ static const QString FormDataFolder(); /** * Request to the wallet service to change the password of * the wallet @p name. * @param name The wallet to change the password of. * @param w The window id to associate any dialogs with. You can pass * 0 if you don't have a window the password dialog should * associate with. */ static void changePassword(const QString &name, WId w); /** * This syncs the wallet file on disk with what is in memory. * You don't normally need to use this. It happens * automatically on close. * @return Returns 0 on success, non-zero on error. */ virtual int sync(); /** * This closes and locks the current wallet. It will * disconnect all applications using the wallet. * @return Returns 0 on success, non-zero on error. */ virtual int lockWallet(); /** * The name of the current wallet. */ virtual const QString &walletName() const; /** * Determine if the current wallet is open, and is a valid * wallet handle. * @return Returns true if the wallet handle is valid and open. */ virtual bool isOpen() const; /** * Request to the wallet service to change the password of * the current wallet. * @param w The window id to associate any dialogs with. You can pass * 0 if you don't have a window the password dialog should * associate with. */ virtual void requestChangePassword(WId w); /** * Obtain the list of all folders contained in the wallet. * @return Returns an empty list if the wallet is not open. */ virtual QStringList folderList(); /** * Determine if the folder @p f exists in the wallet. * @param f the name of the folder to check for * @return Returns true if the folder exists in the wallet. */ virtual bool hasFolder(const QString &f); /** * Set the current working folder to @p f. The folder must * exist, or this call will fail. Create a folder with * createFolder(). * @param f the name of the folder to make the working folder * @return Returns true if the folder was successfully set. */ virtual bool setFolder(const QString &f); /** * Remove the folder @p f and all its entries from the wallet. * @param f the name of the folder to remove * @return Returns true if the folder was successfully removed. */ virtual bool removeFolder(const QString &f); /** * Created the folder @p f. * @param f the name of the folder to create * @return Returns true if the folder was successfully created. */ virtual bool createFolder(const QString &f); /** * Determine the current working folder in the wallet. * If the folder name is empty, it is working in the global * folder, which is valid but discouraged. * @return Returns the current working folder. */ virtual const QString ¤tFolder() const; /** * Return the list of keys of all entries in this folder. * @return Returns an empty list if the wallet is not open, or * if the folder is empty. */ virtual QStringList entryList(); // TODO KDE5: a entryList(folder) so that kwalletmanager can list a folder without // having to call setFolder before and after (which calls contains() in each) /** * Rename the entry @p oldName to @p newName. * @param oldName The original key of the entry. * @param newName The new key of the entry. * @return Returns 0 on success, non-zero on error. */ virtual int renameEntry(const QString &oldName, const QString &newName); /** * Read the entry @p key from the current folder. * The entry format is unknown except that it is either a * QByteArray or a QDataStream, which effectively means that * it is anything. * @param key The key of the entry to read. * @param value A buffer to fill with the value. * @return Returns 0 on success, non-zero on error. */ virtual int readEntry(const QString &key, QByteArray &value); /** * Read the map entry @p key from the current folder. * @param key The key of the entry to read. * @param value A map buffer to fill with the value. * @return Returns 0 on success, non-zero on error. Will * return an error if the key was not originally * written as a map. */ virtual int readMap(const QString &key, QMap &value); /** * Read the password entry @p key from the current folder. * @param key The key of the entry to read. * @param value A password buffer to fill with the value. * @return Returns 0 on success, non-zero on error. Will * return an error if the key was not originally * written as a password. */ virtual int readPassword(const QString &key, QString &value); +#if KWALLET_ENABLE_DEPRECATED_SINCE(5, 70) /** * Read the entries matching @p key from the current folder. * The entry format is unknown except that it is either a * QByteArray or a QDataStream, which effectively means that * it is anything. * @param key The key of the entry to read. Wildcards * are supported. * @param value A buffer to fill with the value. The key in * the map is the entry key. * @return Returns 0 on success, non-zero on error. + * + * @deprecated Since 5.70, use entriesList() */ int readEntryList(const QString &key, QMap &value); /** * Read the map entry @p key from the current folder. * @param key The key of the entry to read. Wildcards * are supported. * @param value A buffer to fill with the value. The key in * the map is the entry key. * @return Returns 0 on success, non-zero on error. Will * return an error if the key was not originally * written as a map. + * + * @deprecated Since 5.70, use mapList() */ int readMapList(const QString &key, QMap > &value); /** * Read the password entry @p key from the current folder. * @param key The key of the entry to read. Wildcards * are supported. * @param value A buffer to fill with the value. The key in * the map is the entry key. * @return Returns 0 on success, non-zero on error. Will * return an error if the key was not originally * written as a password. + * + * @deprecated Since 5.70, use passwordList() */ int readPasswordList(const QString &key, QMap &value); +#endif + + /** + * Get a list of all the entries in the current folder. The entry + * format is unknown except that it is either a QByteArray or a + * QDataStream, which effectively means that it could be anything. + * + * @param value A buffer to fill with the value. The key in the map + * is the entry key. + * @return Returns 0 on success, non-zero on error. + * + * @since 5.70 + */ + int entriesList(QMap &value); + + /** + * Get a list of all the maps in the current folder. + * @param value A buffer to fill with the value. The key in the + * map is the entry key. + * @return Returns 0 on success, non-zero on error. Will return an + * error if any of the keys was not originally written as + * a map. + * + * @since 5.70 + */ + int mapList(QMap > &value); + + /** + * Get a list of all the passwords in the current folder, which can + * be used to populate a list view in a password manager. + * @param value A buffer to fill with the value. The key in the + * map is the entry key. + * @return Returns 0 on success, non-zero on error. Will return an + * error if any of the keys was not originally written as a + * password. + * + * @since 5.70 + */ + int passwordList(QMap &value); /** * Write @p key = @p value as a binary entry to the current * folder. Be careful with this, it could cause inconsistency * in the future since you can put an arbitrary entry type in * place. * @param key The key of the new entry. * @param value The value of the entry. * @param entryType The type of the entry. * @return Returns 0 on success, non-zero on error. */ virtual int writeEntry(const QString &key, const QByteArray &value, EntryType entryType); /** * Write @p key = @p value as a binary entry to the current * folder. * @param key The key of the new entry. * @param value The value of the entry. * @return Returns 0 on success, non-zero on error. */ virtual int writeEntry(const QString &key, const QByteArray &value); /** * Write @p key = @p value as a map to the current folder. * @param key The key of the new entry. * @param value The value of the map. * @return Returns 0 on success, non-zero on error. */ virtual int writeMap(const QString &key, const QMap &value); /** * Write @p key = @p value as a password to the current folder. * @param key The key of the new entry. * @param value The value of the password. * @return Returns 0 on success, non-zero on error. */ virtual int writePassword(const QString &key, const QString &value); /** * Determine if the current folder has they entry @p key. * @param key The key to search for. * @return Returns true if the folder contains @p key. */ virtual bool hasEntry(const QString &key); /** * Remove the entry @p key from the current folder. * @param key The key to remove. * @return Returns 0 on success, non-zero on error. */ virtual int removeEntry(const QString &key); /** * Determine the type of the entry @p key in this folder. * @param key The key to look up. * @return Returns an enumerated type representing the type * of the entry. */ virtual EntryType entryType(const QString &key); /** * Determine if a folder does not exist in a wallet. This * does not require decryption of the wallet. * This is a handy optimization to avoid prompting the user * if your data is certainly not in the wallet. * @param wallet The wallet to look in. * @param folder The folder to look up. * @return Returns true if the folder does NOT exist in the * wallet, or the wallet does not exist. */ static bool folderDoesNotExist(const QString &wallet, const QString &folder); /** * Determine if an entry in a folder does not exist in a * wallet. This does not require decryption of the wallet. * This is a handy optimization to avoid prompting the user * if your data is certainly not in the wallet. * @param wallet The wallet to look in. * @param folder The folder to look in. * @param key The key to look up. * @return Returns true if the key does NOT exist in the * wallet, or the folder or wallet does not exist. */ static bool keyDoesNotExist(const QString &wallet, const QString &folder, const QString &key); /** * Determine if the KWallet API is using the KSecretsService infrastructure * This can ben changed in system settings * @return Returns true if the KSecretsService infrastructure is active */ static bool isUsingKSecretsService(); Q_SIGNALS: /** * Emitted when this wallet is closed. */ void walletClosed(); /** * Emitted when a folder in this wallet is updated. * @param folder The folder that was updated. */ void folderUpdated(const QString &folder); /** * Emitted when the folder list is changed in this wallet. */ void folderListUpdated(); /** * Emitted when a folder in this wallet is removed. * @param folder The folder that was removed. */ void folderRemoved(const QString &folder); /** * Emitted when a wallet is opened in asynchronous mode. * @param success True if the wallet was opened successfully. */ void walletOpened(bool success); private Q_SLOTS: /** * @internal * D-Bus slot for signals emitted by the wallet service. */ void slotWalletClosed(int handle); /** * @internal * D-Bus slot for signals emitted by the wallet service. */ void slotFolderUpdated(const QString &wallet, const QString &folder); /** * @internal * D-Bus slot for signals emitted by the wallet service. */ void slotFolderListUpdated(const QString &wallet); /** * @internal * D-Bus slot for signals emitted by the wallet service. */ void slotApplicationDisconnected(const QString &wallet, const QString &application); /** * @internal * Callback for kwalletd * @param tId identifer for the open transaction * @param handle the wallet's handle */ void walletAsyncOpened(int tId, int handle); /** * @internal * D-Bus error slot. */ void emitWalletAsyncOpenError(); /** * @internal * Emits wallet opening success. */ void emitWalletOpened(); /** * @internal * Receives status changed notifications from KSecretsService infrastructure */ void slotCollectionStatusChanged(int); /** * @internal * Received delete notification from KSecretsService infrastructure */ void slotCollectionDeleted(); private: class WalletPrivate; WalletPrivate *const d; Q_PRIVATE_SLOT(d, void walletServiceUnregistered()) protected: /** * @internal */ virtual void virtual_hook(int id, void *data); }; } #endif //_KWALLET_H diff --git a/src/api/KWallet/org.kde.KWallet.xml b/src/api/KWallet/org.kde.KWallet.xml index ec4bd6e..69dcd1d 100644 --- a/src/api/KWallet/org.kde.KWallet.xml +++ b/src/api/KWallet/org.kde.KWallet.xml @@ -1,276 +1,297 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/runtime/kwalletd/backend/kwalletbackend.cc b/src/runtime/kwalletd/backend/kwalletbackend.cc index a6c4adb..ea8ff24 100644 --- a/src/runtime/kwalletd/backend/kwalletbackend.cc +++ b/src/runtime/kwalletd/backend/kwalletbackend.cc @@ -1,727 +1,743 @@ /* This file is part of the KDE project * * Copyright (C) 2001-2004 George Staikos * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kwalletbackend.h" #include "kwalletbackend_debug.h" #include #include #ifdef HAVE_GPGMEPP #include #endif #include #include #include #include #include #include #include #include #include #include #include #include "blowfish.h" #include "sha1.h" #include "cbc.h" #include // quick fix to get random numbers on win32 #ifdef Q_OS_WIN //krazy:exclude=cpp #include #include #endif #define KWALLET_VERSION_MAJOR 0 #define KWALLET_VERSION_MINOR 1 using namespace KWallet; #define KWMAGIC "KWALLET\n\r\0\r\n" class Backend::BackendPrivate { }; // static void initKWalletDir() // { // KGlobal::dirs()->addResourceType("kwallet", 0, "share/apps/kwallet"); // } Backend::Backend(const QString &name, bool isPath) : d(nullptr), _name(name), _useNewHash(false), _ref(0), _cipherType(KWallet::BACKEND_CIPHER_UNKNOWN) { // initKWalletDir(); if (isPath) { _path = name; } else { _path = getSaveLocation() + QDir::separator() + _name + ".kwl"; } _open = false; } Backend::~Backend() { if (_open) { close(); } delete d; } QString Backend::getSaveLocation() { QString writeLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation); if (writeLocation.right(1) == QLatin1String("5")) { // HACK // setApplicationName("kwalletd5") yields the path ~/.local/share/kwalletd5 for the location where to store wallets // that is not desirable, as the 5 is present in the data folder's name // this workaround getts the right ~/.local/share/kwalletd location writeLocation = writeLocation.left(writeLocation.length() -1); } QDir writeDir(writeLocation); if (!writeDir.exists()) { if (!writeDir.mkpath(writeLocation)) { qFatal("Cannot create wallet save location!"); } } // qCDebug(KWALLETBACKEND_LOG) << "Using saveLocation " + writeLocation; return writeLocation; } void Backend::setCipherType(BackendCipherType ct) { // changing cipher type on already initialed wallets is not permitted assert(_cipherType == KWallet::BACKEND_CIPHER_UNKNOWN); _cipherType = ct; } static int password2PBKDF2_SHA512(const QByteArray &password, QByteArray &hash, const QByteArray &salt) { if (!gcry_check_version("1.5.0")) { printf("libcrypt version is too old \n"); return GPG_ERR_USER_2; } gcry_error_t error; bool static gcry_secmem_init = false; if (!gcry_secmem_init) { error = gcry_control(GCRYCTL_INIT_SECMEM, 32768, 0); if (error != 0) { qWarning() << "Can't get secure memory:" << error; return error; } gcry_secmem_init = true; } gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0); error = gcry_kdf_derive(password.constData(), password.size(), GCRY_KDF_PBKDF2, GCRY_MD_SHA512, salt.data(), salt.size(), PBKDF2_SHA512_ITERATIONS, PBKDF2_SHA512_KEYSIZE, hash.data()); return error; } // this should be SHA-512 for release probably static int password2hash(const QByteArray &password, QByteArray &hash) { SHA1 sha; int shasz = sha.size() / 8; assert(shasz >= 20); QByteArray block1(shasz, 0); sha.process(password.data(), qMin(password.size(), 16)); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block1.data(), sha.hash(), shasz); sha.reset(); sha.process(block1.data(), shasz); } sha.reset(); if (password.size() > 16) { sha.process(password.data() + 16, qMin(password.size() - 16, 16)); QByteArray block2(shasz, 0); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block2.data(), sha.hash(), shasz); sha.reset(); sha.process(block2.data(), shasz); } sha.reset(); if (password.size() > 32) { sha.process(password.data() + 32, qMin(password.size() - 32, 16)); QByteArray block3(shasz, 0); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block3.data(), sha.hash(), shasz); sha.reset(); sha.process(block3.data(), shasz); } sha.reset(); if (password.size() > 48) { sha.process(password.data() + 48, password.size() - 48); QByteArray block4(shasz, 0); // To make brute force take longer for (int i = 0; i < 2000; i++) { memcpy(block4.data(), sha.hash(), shasz); sha.reset(); sha.process(block4.data(), shasz); } sha.reset(); // split 14/14/14/14 hash.resize(56); memcpy(hash.data(), block1.data(), 14); memcpy(hash.data() + 14, block2.data(), 14); memcpy(hash.data() + 28, block3.data(), 14); memcpy(hash.data() + 42, block4.data(), 14); block4.fill(0); } else { // split 20/20/16 hash.resize(56); memcpy(hash.data(), block1.data(), 20); memcpy(hash.data() + 20, block2.data(), 20); memcpy(hash.data() + 40, block3.data(), 16); } block3.fill(0); } else { // split 20/20 hash.resize(40); memcpy(hash.data(), block1.data(), 20); memcpy(hash.data() + 20, block2.data(), 20); } block2.fill(0); } else { // entirely block1 hash.resize(20); memcpy(hash.data(), block1.data(), 20); } block1.fill(0); return 0; } int Backend::deref() { if (--_ref < 0) { qCDebug(KWALLETBACKEND_LOG) << "refCount negative!"; _ref = 0; } return _ref; } bool Backend::exists(const QString &wallet) { QString saveLocation = getSaveLocation(); QString path = saveLocation + '/' + wallet + QLatin1String(".kwl"); // Note: 60 bytes is presently the minimum size of a wallet file. // Anything smaller is junk. return QFile::exists(path) && QFileInfo(path).size() >= 60; } QString Backend::openRCToString(int rc) { switch (rc) { case -255: return i18n("Already open."); case -2: return i18n("Error opening file."); case -3: return i18n("Not a wallet file."); case -4: return i18n("Unsupported file format revision."); case -41: return QStringLiteral("Unknown cipher or hash"); //FIXME: use i18n after string freeze case -42: return i18n("Unknown encryption scheme."); case -43: return i18n("Corrupt file?"); case -8: return i18n("Error validating wallet integrity. Possibly corrupted."); case -5: case -7: case -9: return i18n("Read error - possibly incorrect password."); case -6: return i18n("Decryption error."); default: return QString(); } } int Backend::open(const QByteArray &password, WId w) { if (_open) { return -255; // already open } setPassword(password); return openInternal(w); } #ifdef HAVE_GPGMEPP int Backend::open(const GpgME::Key &key) { if (_open) { return -255; // already open } _gpgKey = key; return openInternal(); } #endif // HAVE_GPGMEPP int Backend::openPreHashed(const QByteArray &passwordHash) { if (_open) { return -255; // already open } // check the password hash for correct size (currently fixed) if (passwordHash.size() != 20 && passwordHash.size() != 40 && passwordHash.size() != 56) { return -42; // unsupported encryption scheme } _passhash = passwordHash; _newPassHash = passwordHash; _useNewHash = true;//Only new hash is supported return openInternal(); } int Backend::openInternal(WId w) { // No wallet existed. Let's create it. // Note: 60 bytes is presently the minimum size of a wallet file. // Anything smaller is junk and should be deleted. if (!QFile::exists(_path) || QFileInfo(_path).size() < 60) { QFile newfile(_path); if (!newfile.open(QIODevice::ReadWrite)) { return -2; // error opening file } newfile.close(); _open = true; if (sync(w) != 0) { return -2; } } QFile db(_path); if (!db.open(QIODevice::ReadOnly)) { return -2; // error opening file } char magicBuf[KWMAGIC_LEN]; db.read(magicBuf, KWMAGIC_LEN); if (memcmp(magicBuf, KWMAGIC, KWMAGIC_LEN) != 0) { return -3; // bad magic } db.read(magicBuf, 4); // First byte is major version, second byte is minor version if (magicBuf[0] != KWALLET_VERSION_MAJOR) { return -4; // unknown version } //0 has been the MINOR version until 4.13, from that point we use it to upgrade the hash if (magicBuf[1] == 1) { qCDebug(KWALLETBACKEND_LOG) << "Wallet new enough, using new hash"; swapToNewHash(); } else if (magicBuf[1] != 0) { qCDebug(KWALLETBACKEND_LOG) << "Wallet is old, sad panda :("; return -4; // unknown version } BackendPersistHandler *phandler = BackendPersistHandler::getPersistHandler(magicBuf); if (nullptr == phandler) { return -41; // unknown cipher or hash } int result = phandler->read(this, db, w); delete phandler; return result; } void Backend::swapToNewHash() { //Runtime error happened and we can't use the new hash if (!_useNewHash) { qCDebug(KWALLETBACKEND_LOG) << "Runtime error on the new hash"; return; } _passhash.fill(0);//Making sure the old passhash is not around in memory _passhash = _newPassHash;//Use the new hash, means the wallet is modern enough } QByteArray Backend::createAndSaveSalt(const QString &path) const { QFile saltFile(path); saltFile.remove(); if (!saltFile.open(QIODevice::WriteOnly)) { return QByteArray(); } saltFile.setPermissions(QFile::ReadUser | QFile::WriteUser); char *randomData = (char *) gcry_random_bytes(PBKDF2_SHA512_SALTSIZE, GCRY_STRONG_RANDOM); QByteArray salt(randomData, PBKDF2_SHA512_SALTSIZE); free(randomData); if (saltFile.write(salt) != PBKDF2_SHA512_SALTSIZE) { return QByteArray(); } saltFile.close(); return salt; } int Backend::sync(WId w) { if (!_open) { return -255; // not open yet } if (!QFile::exists(_path)) { return -3; // File does not exist } QSaveFile sf(_path); if (!sf.open(QIODevice::WriteOnly | QIODevice::Unbuffered)) { return -1; // error opening file } sf.setPermissions(QFile::ReadUser | QFile::WriteUser); if (sf.write(KWMAGIC, KWMAGIC_LEN) != KWMAGIC_LEN) { sf.cancelWriting(); return -4; // write error } // Write the version number QByteArray version(4, 0); version[0] = KWALLET_VERSION_MAJOR; if (_useNewHash) { version[1] = KWALLET_VERSION_MINOR; //Use the sync to update the hash to PBKDF2_SHA512 swapToNewHash(); } else { version[1] = 0; //was KWALLET_VERSION_MINOR before the new hash } BackendPersistHandler *phandler = BackendPersistHandler::getPersistHandler(_cipherType); if (nullptr == phandler) { return -4; // write error } int rc = phandler->write(this, sf, version, w); if (rc < 0) { // Oops! wallet file sync filed! Display a notification about that // TODO: change kwalletd status flags, when status flags will be implemented KNotification *notification = new KNotification(QStringLiteral("syncFailed")); notification->setText(i18n("Failed to sync wallet %1 to disk. Error codes are:\nRC %2\nSF %3. Please file a BUG report using this information to bugs.kde.org").arg(_name).arg(rc).arg(sf.errorString())); notification->sendEvent(); } delete phandler; return rc; } int Backend::close(bool save) { // save if requested if (save) { int rc = sync(0); if (rc != 0) { return rc; } } // do the actual close for (FolderMap::ConstIterator i = _entries.constBegin(); i != _entries.constEnd(); ++i) { for (EntryMap::ConstIterator j = i.value().constBegin(); j != i.value().constEnd(); ++j) { delete j.value(); } } _entries.clear(); // empty the password hash _passhash.fill(0); _newPassHash.fill(0); _open = false; return 0; } const QString &Backend::walletName() const { return _name; } bool Backend::isOpen() const { return _open; } QStringList Backend::folderList() const { return _entries.keys(); } QStringList Backend::entryList() const { return _entries[_folder].keys(); } Entry *Backend::readEntry(const QString &key) { Entry *rc = nullptr; if (_open && hasEntry(key)) { rc = _entries[_folder][key]; } return rc; } +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) QList Backend::readEntryList(const QString &key) { QList rc; if (!_open) { return rc; } // HACK: see Wallet::WalletPrivate::forEachItemThatMatches() const QString pattern = QRegularExpression::wildcardToRegularExpression(key).replace( QLatin1String("[^/]"), QLatin1String(".")); const QRegularExpression re(pattern); const EntryMap &map = _entries[_folder]; for (EntryMap::ConstIterator i = map.begin(); i != map.end(); ++i) { if (re.match(i.key()).hasMatch()) { rc.append(i.value()); } } return rc; } +#endif + +QList Backend::entriesList() +{ + QList rc; + + if (!_open) { + return rc; + } + const EntryMap &map = _entries[_folder]; + rc.append(map.values()); + + return rc; +} + bool Backend::createFolder(const QString &f) { if (_entries.contains(f)) { return false; } _entries.insert(f, EntryMap()); QCryptographicHash folderMd5(QCryptographicHash::Md5); folderMd5.addData(f.toUtf8()); _hashes.insert(MD5Digest(folderMd5.result()), QList()); return true; } int Backend::renameEntry(const QString &oldName, const QString &newName) { EntryMap &emap = _entries[_folder]; EntryMap::Iterator oi = emap.find(oldName); EntryMap::Iterator ni = emap.find(newName); if (oi != emap.end() && ni == emap.end()) { Entry *e = oi.value(); emap.erase(oi); emap[newName] = e; QCryptographicHash folderMd5(QCryptographicHash::Md5); folderMd5.addData(_folder.toUtf8()); HashMap::iterator i = _hashes.find(MD5Digest(folderMd5.result())); if (i != _hashes.end()) { QCryptographicHash oldMd5(QCryptographicHash::Md5), newMd5(QCryptographicHash::Md5); oldMd5.addData(oldName.toUtf8()); newMd5.addData(newName.toUtf8()); i.value().removeAll(MD5Digest(oldMd5.result())); i.value().append(MD5Digest(newMd5.result())); } return 0; } return -1; } void Backend::writeEntry(Entry *e) { if (!_open) { return; } if (!hasEntry(e->key())) { _entries[_folder][e->key()] = new Entry; } _entries[_folder][e->key()]->copy(e); QCryptographicHash folderMd5(QCryptographicHash::Md5); folderMd5.addData(_folder.toUtf8()); HashMap::iterator i = _hashes.find(MD5Digest(folderMd5.result())); if (i != _hashes.end()) { QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(e->key().toUtf8()); i.value().append(MD5Digest(md5.result())); } } bool Backend::hasEntry(const QString &key) const { return _entries.contains(_folder) && _entries[_folder].contains(key); } bool Backend::removeEntry(const QString &key) { if (!_open) { return false; } FolderMap::Iterator fi = _entries.find(_folder); EntryMap::Iterator ei = fi.value().find(key); if (fi != _entries.end() && ei != fi.value().end()) { delete ei.value(); fi.value().erase(ei); QCryptographicHash folderMd5(QCryptographicHash::Md5); folderMd5.addData(_folder.toUtf8()); HashMap::iterator i = _hashes.find(MD5Digest(folderMd5.result())); if (i != _hashes.end()) { QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(key.toUtf8()); i.value().removeAll(MD5Digest(md5.result())); } return true; } return false; } bool Backend::removeFolder(const QString &f) { if (!_open) { return false; } FolderMap::Iterator fi = _entries.find(f); if (fi != _entries.end()) { if (_folder == f) { _folder.clear(); } for (EntryMap::Iterator ei = fi.value().begin(); ei != fi.value().end(); ++ei) { delete ei.value(); } _entries.erase(fi); QCryptographicHash folderMd5(QCryptographicHash::Md5); folderMd5.addData(f.toUtf8()); _hashes.remove(MD5Digest(folderMd5.result())); return true; } return false; } bool Backend::folderDoesNotExist(const QString &folder) const { QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(folder.toUtf8()); return !_hashes.contains(MD5Digest(md5.result())); } bool Backend::entryDoesNotExist(const QString &folder, const QString &entry) const { QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(folder.toUtf8()); HashMap::const_iterator i = _hashes.find(MD5Digest(md5.result())); if (i != _hashes.end()) { md5.reset(); md5.addData(entry.toUtf8()); return !i.value().contains(MD5Digest(md5.result())); } return true; } void Backend::setPassword(const QByteArray &password) { _passhash.fill(0); // empty just in case BlowFish _bf; CipherBlockChain bf(&_bf); _passhash.resize(bf.keyLen() / 8); _newPassHash.resize(bf.keyLen() / 8); _newPassHash.fill(0); password2hash(password, _passhash); QByteArray salt; QFile saltFile(getSaveLocation() + QDir::separator() + _name + ".salt"); if (!saltFile.exists() || saltFile.size() == 0) { salt = createAndSaveSalt(saltFile.fileName()); } else { if (!saltFile.open(QIODevice::ReadOnly)) { salt = createAndSaveSalt(saltFile.fileName()); } else { salt = saltFile.readAll(); } } if (!salt.isEmpty() && password2PBKDF2_SHA512(password, _newPassHash, salt) == 0) { qCDebug(KWALLETBACKEND_LOG) << "Setting useNewHash to true"; _useNewHash = true; } } #ifdef HAVE_GPGMEPP const GpgME::Key &Backend::gpgKey() const { return _gpgKey; } #endif diff --git a/src/runtime/kwalletd/backend/kwalletbackend.h b/src/runtime/kwalletd/backend/kwalletbackend.h index 30a8055..1a550ae 100644 --- a/src/runtime/kwalletd/backend/kwalletbackend.h +++ b/src/runtime/kwalletd/backend/kwalletbackend.h @@ -1,225 +1,233 @@ /* This file is part of the KDE project * * Copyright (C) 2001-2004 George Staikos * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef _KWALLETBACKEND_H #define _KWALLETBACKEND_H #include #include #include #include "kwalletentry.h" #include "backendpersisthandler.h" #include "kwalletbackend5_export.h" #ifdef HAVE_GPGMEPP #include #endif // HAVE_GPGMEPP #define PBKDF2_SHA512_KEYSIZE 56 #define PBKDF2_SHA512_SALTSIZE 56 #define PBKDF2_SHA512_ITERATIONS 50000 namespace KWallet { /** * @internal */ class MD5Digest : public QByteArray { public: MD5Digest() : QByteArray(16, 0) {} MD5Digest(const char *data) : QByteArray(data, 16) {} MD5Digest(const QByteArray &digest) : QByteArray(digest) {} virtual ~MD5Digest() {} int operator<(const MD5Digest &r) const { int i = 0; char x, y; for (; i < 16; ++i) { x = at(i); y = r.at(i); if (x != y) { break; } } if (i < 16 && x < y) { return 1; } return 0; } }; /* @internal */ class KWALLETBACKEND5_EXPORT Backend { public: explicit Backend(const QString &name = QStringLiteral("kdewallet"), bool isPath = false); ~Backend(); // Open and unlock the wallet. // If opening succeeds, the password's hash will be remembered. // If opening fails, the password's hash will be cleared. int open(const QByteArray &password, WId w = 0); #ifdef HAVE_GPGMEPP int open(const GpgME::Key &key); #endif // Open and unlock the wallet using a pre-hashed password. // If opening succeeds, the password's hash will be remembered. // If opening fails, the password's hash will be cleared. int openPreHashed(const QByteArray &passwordHash); // Close the wallet, losing any changes. // if save is true, the wallet is saved prior to closing it. int close(bool save = false); // Write the wallet to disk int sync(WId w); // Returns true if the current wallet is open. bool isOpen() const; // Returns the current wallet name. const QString &walletName() const; // The list of folders. QStringList folderList() const; // Force creation of a folder. bool createFolder(const QString &f); // Change the folder. void setFolder(const QString &f) { _folder = f; } // Current folder. If empty, it's the global folder. const QString &folder() const { return _folder; } // Does it have this folder? bool hasFolder(const QString &f) const { return _entries.contains(f); } // Look up an entry. Returns null if it doesn't exist. Entry *readEntry(const QString &key); +#if KWALLET_ENABLE_DEPRECATED_SINCE(5, 70) // Look up a list of entries. Supports wildcards. - // You delete the list + // You delete the list. + // Deprecated since 5.70, use entriesList() QList readEntryList(const QString &key); +#endif + + // Get a list of all the entries in the current folder. + // You delete the list. + // @since 5.70 + QList entriesList(); // Store an entry. void writeEntry(Entry *e); // Does this folder contain this entry? bool hasEntry(const QString &key) const; // Returns true if the entry was removed bool removeEntry(const QString &key); // Returns true if the folder was removed bool removeFolder(const QString &f); // The list of entries in this folder. QStringList entryList() const; // Rename an entry in this folder. int renameEntry(const QString &oldName, const QString &newName); // Set the password used for opening/closing the wallet. // This does not sync the wallet to disk! void setPassword(const QByteArray &password); int ref() { return ++_ref; } int deref(); int refCount() const { return _ref; } static bool exists(const QString &wallet); bool folderDoesNotExist(const QString &folder) const; bool entryDoesNotExist(const QString &folder, const QString &entry) const; static QString openRCToString(int rc); void setCipherType(BackendCipherType ct); BackendCipherType cipherType() const { return _cipherType; } #ifdef HAVE_GPGMEPP const GpgME::Key &gpgKey() const; #endif static QString getSaveLocation(); private: Q_DISABLE_COPY(Backend) class BackendPrivate; BackendPrivate *const d; QString _name; QString _path; bool _open; bool _useNewHash; QString _folder; int _ref; // Map Folder->Entries typedef QMap< QString, Entry * > EntryMap; typedef QMap< QString, EntryMap > FolderMap; FolderMap _entries; typedef QMap > HashMap; HashMap _hashes; QByteArray _passhash; // password hash used for saving the wallet QByteArray _newPassHash; //Modern hash using KWALLET_HASH_PBKDF2_SHA512 BackendCipherType _cipherType; // the kind of encryption used for this wallet #ifdef HAVE_GPGMEPP GpgME::Key _gpgKey; #endif friend class BlowfishPersistHandler; friend class GpgPersistHandler; // open the wallet with the password already set. This is // called internally by both open and openPreHashed. int openInternal(WId w = 0); void swapToNewHash(); QByteArray createAndSaveSalt(const QString &path) const; }; } #endif diff --git a/src/runtime/kwalletd/kwalletd.cpp b/src/runtime/kwalletd/kwalletd.cpp index b052aaf..5c9b111 100644 --- a/src/runtime/kwalletd/kwalletd.cpp +++ b/src/runtime/kwalletd/kwalletd.cpp @@ -1,1927 +1,1986 @@ /* This file is part of the KDE libraries Copyright (c) 2002-2004 George Staikos Copyright (c) 2008 Michael Leupold This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kwalletd.h" #include "kwalletd_debug.h" #include "kbetterthankdialog.h" #include "kwalletwizard.h" #ifdef HAVE_GPGMEPP #include "knewwalletdialog.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_GPGMEPP #include #endif #include #include #include #include #include #include #include #include "kwalletadaptor.h" class KWalletTransaction { public: explicit KWalletTransaction(QDBusConnection conn) : tType(Unknown) , cancelled(false) , tId(nextTransactionId) , res(-1) , connection(conn) { nextTransactionId++; // make sure the id is never < 0 as that's used for the // error conditions. if (nextTransactionId < 0) { nextTransactionId = 0; } } ~KWalletTransaction() {} enum Type { Unknown, Open, ChangePassword, OpenFail, CloseCancelled }; Type tType; QString appid; qlonglong wId; QString wallet; QString service; bool cancelled; // set true if the client dies before open bool modal; bool isPath; int tId; // transaction id int res; QDBusMessage message; QDBusConnection connection; private: static int nextTransactionId; }; int KWalletTransaction::nextTransactionId = 0; KWalletD::KWalletD() : QObject(nullptr) , _failed(0) , _syncTime(5000) , _curtrans(nullptr) , _useGpg(false) { #ifdef HAVE_GPGMEPP _useGpg = true; #endif srand(time(nullptr)); _showingFailureNotify = false; _closeIdle = false; _idleTime = 0; connect( &_closeTimers, SIGNAL(timedOut(int)), this, SLOT(timedOutClose(int))); connect( &_syncTimers, SIGNAL(timedOut(int)), this, SLOT(timedOutSync(int))); (void)new KWalletAdaptor(this); // register services QDBusConnection::sessionBus().registerService( QStringLiteral("org.kde.kwalletd5")); QDBusConnection::sessionBus().registerObject( QStringLiteral("/modules/kwalletd5"), this); #ifdef Q_WS_X11 screensaver = 0; #endif reconfigure(); // KGlobal::dirs()->addResourceType("kwallet", 0, "share/apps/kwallet"); _dw = new KDirWatch(this); _dw->setObjectName(QStringLiteral("KWallet Directory Watcher")); // _dw->addDir(KGlobal::dirs()->saveLocation("kwallet")); _dw->addDir(KWallet::Backend::getSaveLocation()); _dw->startScan(true); connect(_dw, SIGNAL(dirty(QString)), this, SLOT(emitWalletListDirty())); connect(_dw, &KDirWatch::deleted, this, &KWalletD::emitWalletListDirty); _serviceWatcher.setWatchMode(QDBusServiceWatcher::WatchForOwnerChange); connect(&_serviceWatcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)), this, SLOT(slotServiceOwnerChanged(QString,QString,QString))); } void KWalletD::registerKWalletd4Service() { auto bus = QDBusConnection::sessionBus().interface(); auto reply = bus->registerService(QStringLiteral("org.kde.kwalletd"), QDBusConnectionInterface::QueueService); if (reply.isValid() && (reply.value() == QDBusConnectionInterface::ServiceQueued)) { QDBusInterface _kde_kwalletd4(QStringLiteral("org.kde.kwalletd"), QStringLiteral("/MainApplication"), QStringLiteral("org.kde.KApplication")); if (_kde_kwalletd4.isValid()) { auto qreply = _kde_kwalletd4.call(QStringLiteral("quit")); } } QDBusConnection::sessionBus().registerObject(QStringLiteral("/modules/kwalletd"), this); } KWalletD::~KWalletD() { #ifdef Q_WS_X11 delete screensaver; screensaver = 0; #endif closeAllWallets(); qDeleteAll(_transactions); } #ifdef Q_WS_X11 void KWalletD::connectToScreenSaver() { screensaver = new QDBusInterface("org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver"); if (!screensaver->isValid()) { qCDebug(KWALLETD_LOG) << "Service org.freedesktop.ScreenSaver not found. Retrying in 10 seconds..."; // keep attempting every 10 seconds QTimer::singleShot(10000, this, SLOT(connectToScreenSaver())); } else { connect(screensaver, SIGNAL(ActiveChanged(bool)), SLOT(screenSaverChanged(bool))); qCDebug(KWALLETD_LOG) << "connected to screen saver service."; } } #endif int KWalletD::generateHandle() { int rc; // ASSUMPTION: RAND_MAX is fairly large. do { rc = rand(); } while (_wallets.contains(rc) || rc == 0); return rc; } QPair KWalletD::findWallet( const QString& walletName) const { Wallets::const_iterator it = _wallets.constBegin(); const Wallets::const_iterator end = _wallets.constEnd(); for (; it != end; ++it) { if (it.value()->walletName() == walletName) { return qMakePair(it.key(), it.value()); } } return qMakePair(-1, static_cast(nullptr)); } const QRegularExpression walletRegex( QStringLiteral("^[\\w\\^\\&\\'\\@\\{\\}\\[\\]\\,\\$\\=\\!\\-\\#\\(\\)\\%\\.\\+\\_\\s]+$")); bool KWalletD::_processing = false; void KWalletD::processTransactions() { if (_processing) { return; } _processing = true; // Process remaining transactions while (!_transactions.isEmpty()) { _curtrans = _transactions.takeFirst(); int res; assert(_curtrans->tType != KWalletTransaction::Unknown); switch (_curtrans->tType) { case KWalletTransaction::Open: res = doTransactionOpen(_curtrans->appid, _curtrans->wallet, _curtrans->isPath, _curtrans->wId, _curtrans->modal, _curtrans->service); // multiple requests from the same client // should not produce multiple password // dialogs on a failure if (res < 0) { QList::iterator it; for (it = _transactions.begin(); it != _transactions.end(); ++it) { KWalletTransaction* x = *it; if (_curtrans->appid == x->appid && x->tType == KWalletTransaction::Open && x->wallet == _curtrans->wallet && x->wId == _curtrans->wId) { x->tType = KWalletTransaction::OpenFail; } } } else if (_curtrans->cancelled) { // the wallet opened successfully but the application // opening exited/crashed while the dialog was still shown. KWalletTransaction* _xact = new KWalletTransaction(_curtrans->connection); _xact->tType = KWalletTransaction::CloseCancelled; _xact->appid = _curtrans->appid; _xact->wallet = _curtrans->wallet; _xact->service = _curtrans->service; _transactions.append(_xact); } // emit the AsyncOpened signal as a reply _curtrans->res = res; emit walletAsyncOpened(_curtrans->tId, res); break; case KWalletTransaction::OpenFail: // emit the AsyncOpened signal with an invalid handle _curtrans->res = -1; emit walletAsyncOpened(_curtrans->tId, -1); break; case KWalletTransaction::ChangePassword: doTransactionChangePassword( _curtrans->appid, _curtrans->wallet, _curtrans->wId); break; case KWalletTransaction::CloseCancelled: doTransactionOpenCancelled( _curtrans->appid, _curtrans->wallet, _curtrans->service); break; case KWalletTransaction::Unknown: break; default: break; } // send delayed dbus message reply to the caller if (_curtrans->message.type() != QDBusMessage::InvalidMessage) { if (_curtrans->connection.isConnected()) { QDBusMessage reply = _curtrans->message.createReply(); reply << _curtrans->res; _curtrans->connection.send(reply); } } delete _curtrans; _curtrans = nullptr; } _processing = false; } int KWalletD::openPath( const QString& path, qlonglong wId, const QString& appid) { int tId = openPathAsync(path, wId, appid, false); if (tId < 0) { return tId; } // NOTE the real return value will be sent by the dbusmessage delayed // reply return 0; // wait for the open-transaction to be processed // KWalletOpenLoop loop(this); // return loop.waitForAsyncOpen(tId); } int KWalletD::open(const QString& wallet, qlonglong wId, const QString& appid) { if (!_enabled) { // guard return -1; } if (!walletRegex.match(wallet).hasMatch()) { return -1; } KWalletTransaction* xact = new KWalletTransaction(connection()); _transactions.append(xact); message().setDelayedReply(true); xact->message = message(); xact->appid = appid; xact->wallet = wallet; xact->wId = wId; xact->modal = true; // mark dialogs as modal, the app has blocking wait xact->tType = KWalletTransaction::Open; xact->isPath = false; QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); // NOTE the real return value will be sent by the dbusmessage delayed // reply return 0; } int KWalletD::openAsync(const QString& wallet, qlonglong wId, const QString& appid, bool handleSession) { if (!_enabled) { // guard return -1; } if (!walletRegex.match(wallet).hasMatch()) { return -1; } KWalletTransaction* xact = new KWalletTransaction(connection()); _transactions.append(xact); xact->appid = appid; xact->wallet = wallet; xact->wId = wId; xact->modal = true; // mark dialogs as modal, the app has blocking wait xact->tType = KWalletTransaction::Open; xact->isPath = false; if (handleSession) { qCDebug(KWALLETD_LOG) << "openAsync for " << message().service(); _serviceWatcher.setConnection(connection()); _serviceWatcher.addWatchedService(message().service()); xact->service = message().service(); } QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); // opening is in progress. return the transaction number return xact->tId; } int KWalletD::openPathAsync(const QString& path, qlonglong wId, const QString& appid, bool handleSession) { if (!_enabled) { // gaurd return -1; } KWalletTransaction* xact = new KWalletTransaction(connection()); _transactions.append(xact); xact->appid = appid; xact->wallet = path; xact->wId = wId; xact->modal = true; xact->tType = KWalletTransaction::Open; xact->isPath = true; if (handleSession) { qCDebug(KWALLETD_LOG) << "openPathAsync " << message().service(); _serviceWatcher.setConnection(connection()); _serviceWatcher.addWatchedService(message().service()); xact->service = message().service(); } QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); // opening is in progress. return the transaction number return xact->tId; } // Sets up a dialog that will be shown by kwallet. void KWalletD::setupDialog( QWidget* dialog, WId wId, const QString& appid, bool modal) { if (wId != 0) { // correct, set dialog parent dialog->setAttribute(Qt::WA_NativeWindow, true); KWindowSystem::setMainWindow(dialog->windowHandle(), wId); } else { if (appid.isEmpty()) { qWarning() << "Using kwallet without parent window!"; } else { qWarning() << "Application '" << appid << "' using kwallet without parent window!"; } // allow dialog activation even if it interrupts, better than trying // hacks // with keeping the dialog on top or on all desktops // KF5 FIXME what should we use now instead of this: // kapp->updateUserTimestamp(); } if (modal) { KWindowSystem::setState(dialog->winId(), NET::Modal); } else { KWindowSystem::clearState(dialog->winId(), NET::Modal); } activeDialog = dialog; } // If there's a dialog already open and another application tries some // operation that'd lead to // opening a dialog, that application will be blocked by this dialog. A proper // solution would // be to set the second application's window also as a parent for the active // dialog, so that // KWin properly handles focus changes and so on, but there's currently no // support for multiple // dialog parents. In the absence of this support, we use all kinds of bad // hacks to make // sure the user doesn't overlook the active dialog. void KWalletD::checkActiveDialog() { if (!activeDialog) { return; } // KF5 FIXME what should we use now instead of this: // kapp->updateUserTimestamp(); activeDialog->show(); WId window = activeDialog->winId(); KWindowSystem::setState(window, NET::KeepAbove); KWindowSystem::setOnAllDesktops(window, true); KWindowSystem::forceActiveWindow(window); KWindowSystem::raiseWindow(window); } int KWalletD::doTransactionOpen(const QString& appid, const QString& wallet, bool isPath, qlonglong wId, bool modal, const QString& service) { if (_firstUse && !isPath) { // if the user specifies a wallet name, the use it as the default // wallet name if (wallet != KWallet::Wallet::LocalWallet()) { KConfig kwalletrc(QStringLiteral("kwalletrc")); KConfigGroup cfg(&kwalletrc, "Wallet"); cfg.writeEntry("Default Wallet", wallet); } if (wallets().contains(KWallet::Wallet::LocalWallet())) { KConfig kwalletrc(QStringLiteral("kwalletrc")); KConfigGroup cfg(&kwalletrc, "Wallet"); _firstUse = false; cfg.writeEntry("First Use", false); } // else { // // First use wizard // // TODO GPG adjust new smartcard options gathered by // the wizard // QPointer wiz = new KWalletWizard(0); // wiz->setWindowTitle(i18n("KDE Wallet Service")); // setupDialog(wiz, (WId)wId, appid, modal); // int rc = wiz->exec(); // if (rc == QDialog::Accepted && wiz) { // bool useWallet = wiz->field("useWallet").toBool(); // KConfig kwalletrc("kwalletrc"); // KConfigGroup cfg(&kwalletrc, "Wallet"); // cfg.writeEntry("First Use", false); // cfg.writeEntry("Enabled", useWallet); // cfg.writeEntry("Close When Idle", // wiz->field("closeWhenIdle").toBool()); // cfg.writeEntry("Use One Wallet", // !wiz->field("networkWallet").toBool()); // cfg.sync(); // reconfigure(); // // if (!useWallet) { // delete wiz; // return -1; // } // // // Create the wallet // // TODO GPG select the correct wallet type upon // cretion (GPG or blowfish based) // KWallet::Backend *b = new // KWallet::Backend(KWallet::Wallet::LocalWallet()); // #ifdef HAVE_GPGMEPP // if (wiz->field("useBlowfish").toBool()) { // b->setCipherType(KWallet::BACKEND_CIPHER_BLOWFISH); // #endif // QString pass = wiz->field("pass1").toString(); // QByteArray p(pass.toUtf8(), pass.length()); // b->open(p); // p.fill(0); // #ifdef HAVE_GPGMEPP // } else { // assert(wiz->field("useGpg").toBool()); // b->setCipherType(KWallet::BACKEND_CIPHER_GPG); // b->open(wiz->gpgKey()); // } // #endif // b->createFolder(KWallet::Wallet::PasswordFolder()); // b->createFolder(KWallet::Wallet::FormDataFolder()); // b->close(true); // delete b; // delete wiz; // } else { // delete wiz; // return -1; // } // } } int rc = internalOpen(appid, wallet, isPath, WId(wId), modal, service); return rc; } int KWalletD::internalOpen(const QString& appid, const QString& wallet, bool isPath, WId w, bool modal, const QString& service) { bool brandNew = false; QString thisApp; if (appid.isEmpty()) { thisApp = QStringLiteral("KDE System"); } else { thisApp = appid; } if (implicitDeny(wallet, thisApp)) { return -1; } QPair walletInfo = findWallet(wallet); int rc = walletInfo.first; if (rc == -1) { if (_wallets.count() > 20) { qCDebug(KWALLETD_LOG) << "Too many wallets open."; return -1; } KWallet::Backend* b = new KWallet::Backend(wallet, isPath); QString password; bool emptyPass = false; if ((isPath && QFile::exists(wallet)) || (!isPath && KWallet::Backend::exists(wallet))) { // this open attempt will set wallet type from the file header, // even if password is needed int pwless = b->open(QByteArray(), w); #ifdef HAVE_GPGMEPP assert(b->cipherType() != KWallet::BACKEND_CIPHER_UNKNOWN); if (b->cipherType() == KWallet::BACKEND_CIPHER_GPG) { // GPG based wallets do not prompt for password here. Instead, // GPG should already have popped pinentry utility for wallet // decryption if (!b->isOpen()) { // for some reason, GPG operation failed delete b; return -1; } emptyPass = true; } else { #endif if (0 != pwless || !b->isOpen()) { if (pwless == 0) { // release, start anew delete b; b = new KWallet::Backend(wallet, isPath); } KPasswordDialog* kpd = new KPasswordDialog(); if (appid.isEmpty()) { kpd->setPrompt( i18n("KDE has requested to open the wallet " "'%1'. Please enter the password for " "this wallet below.", wallet.toHtmlEscaped())); } else { kpd->setPrompt(i18n( "The application '%1' has requested " "to open the wallet '%2'. Please enter " "the password for this wallet below.", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); } brandNew = false; // don't use KStdGuiItem::open() here which has trailing // ellipsis! // KF5 FIXME what should we use now instead of this: // kpd->setButtonGuiItem(KDialog::Ok,KGuiItem( // i18n( "&Open" ), "wallet-open")); kpd->setWindowTitle(i18n("KDE Wallet Service")); kpd->setIcon(QIcon::fromTheme(QStringLiteral("kwalletmanager"))); if (w != KWindowSystem::activeWindow() && w != 0L) { // If the dialog is modal to a minimized window it // might not be visible // (but still blocking the calling application). // Notify the user about // the request to open the wallet. KNotification* notification = new KNotification( QStringLiteral("needsPassword"), kpd, KNotification::Persistent | KNotification::CloseWhenWidgetActivated); QStringList actions; if (appid.isEmpty()) { notification->setText( i18n("An application has requested to open a " "wallet (%1).", wallet.toHtmlEscaped())); actions.append( i18nc("Text of a button for switching to the " "(unnamed) application " "requesting a password", "Switch there")); } else { notification->setText( i18n("%1 has requested to open a " "wallet (%2).", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); actions.append( i18nc("Text of a button for switching to the " "application requesting " "a password", "Switch to %1", appid.toHtmlEscaped())); } notification->setActions(actions); connect(notification, SIGNAL(action1Activated()), this, SLOT(activatePasswordDialog())); notification->sendEvent(); } while (!b->isOpen()) { setupDialog(kpd, w, appid, modal); if (kpd->exec() == QDialog::Accepted) { password = kpd->password(); int rc = b->open(password.toUtf8()); if (!b->isOpen()) { const auto errorStr = KWallet::Backend::openRCToString(rc); qCWarning(KWALLETD_LOG) << "Failed to open wallet" << wallet << errorStr; kpd->setPrompt(i18n( "Error opening the wallet " "'%1'. Please try again.
(Error code %2: %3)
", wallet.toHtmlEscaped(), rc, errorStr)); kpd->setPassword(QLatin1String("")); } } else { break; } } delete kpd; } else { emptyPass = true; } #ifdef HAVE_GPGMEPP } #endif } else { brandNew = true; #ifdef HAVE_GPGMEPP // prompt the user for the new wallet format here KWallet::BackendCipherType newWalletType = KWallet::BACKEND_CIPHER_UNKNOWN; std::shared_ptr newWalletDlg( new KWallet::KNewWalletDialog( appid, wallet, QWidget::find(w))); GpgME::Key gpgKey; setupDialog(newWalletDlg.get(), (WId)w, appid, true); if (newWalletDlg->exec() == QDialog::Accepted) { newWalletType = newWalletDlg->isBlowfish() ? KWallet::BACKEND_CIPHER_BLOWFISH : KWallet::BACKEND_CIPHER_GPG; gpgKey = newWalletDlg->gpgKey(); } else { // user cancelled the dialog box delete b; return -1; } if (newWalletType == KWallet::BACKEND_CIPHER_GPG) { b->setCipherType(newWalletType); b->open(gpgKey); } else if (newWalletType == KWallet::BACKEND_CIPHER_BLOWFISH) { #endif // HAVE_GPGMEPP b->setCipherType(KWallet::BACKEND_CIPHER_BLOWFISH); KNewPasswordDialog* kpd = new KNewPasswordDialog(); KColorScheme colorScheme(QPalette::Active, KColorScheme::View); kpd->setBackgroundWarningColor(colorScheme.background(KColorScheme::NegativeBackground).color()); if (wallet == KWallet::Wallet::LocalWallet() || wallet == KWallet::Wallet::NetworkWallet()) { // Auto create these wallets. if (appid.isEmpty()) { kpd->setPrompt( i18n("KDE has requested to open the wallet. This " "is used to store sensitive data in a " "secure fashion. Please enter a password to " "use with this wallet or click cancel to " "deny the application's request.")); } else { kpd->setPrompt( i18n("The application '%1' has " "requested to open the KDE wallet. This is " "used to store sensitive data in a secure " "fashion. Please enter a password to use " "with this wallet or click cancel to deny " "the application's request.", appid.toHtmlEscaped())); } } else { if (appid.length() == 0) { kpd->setPrompt( i18n("KDE has requested to create a new " "wallet named '%1'. Please choose a " "password for this wallet, or cancel to " "deny the application's request.", wallet.toHtmlEscaped())); } else { kpd->setPrompt(i18n( "The application '%1' has requested " "to create a new wallet named '%2'. " "Please choose a password for this wallet, or " "cancel to deny the application's request.", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); } } kpd->setWindowTitle(i18n("KDE Wallet Service")); // KF5 FIXME what should we use now instead of this: // kpd->setButtonGuiItem(KDialog::Ok,KGuiItem(i18n("C&reate"),"document-new")); kpd->setIcon(QIcon::fromTheme(QStringLiteral("kwalletmanager"))); while (!b->isOpen()) { setupDialog(kpd, w, appid, modal); if (kpd->exec() == QDialog::Accepted) { password = kpd->password(); int rc = b->open(password.toUtf8()); if (!b->isOpen()) { kpd->setPrompt( i18n("Error opening the wallet " "'%1'. Please try again.
(Error code %2: %3)
", wallet.toHtmlEscaped(), rc, KWallet::Backend::openRCToString(rc))); } } else { break; } } delete kpd; #ifdef HAVE_GPGMEPP } #endif } if ((b->cipherType() == KWallet::BACKEND_CIPHER_BLOWFISH) && !emptyPass && (password.isNull() || !b->isOpen())) { delete b; return -1; } if (emptyPass && !isAuthorizedApp(appid, wallet, w)) { delete b; return -1; } _wallets.insert(rc = generateHandle(), b); _sessions.addSession(appid, service, rc); _syncTimers.addTimer(rc, _syncTime); if (brandNew) { createFolder(rc, KWallet::Wallet::PasswordFolder(), appid); createFolder(rc, KWallet::Wallet::FormDataFolder(), appid); } b->ref(); if (_closeIdle) { _closeTimers.addTimer(rc, _idleTime); } if (brandNew) { emit walletCreated(wallet); } emit walletOpened(wallet); if (_wallets.count() == 1 && _launchManager) { KToolInvocation::startServiceByDesktopName( QStringLiteral("kwalletmanager5-kwalletd")); } } else { // prematurely add a reference so that the wallet does not close while // the // authorization dialog is being shown. walletInfo.second->ref(); bool isAuthorized = _sessions.hasSession(appid, rc) || isAuthorizedApp(appid, wallet, w); // as the wallet might have been forcefully closed, find it again to // make sure it's // still available (isAuthorizedApp might show a dialog). walletInfo = findWallet(wallet); if (!isAuthorized) { if (walletInfo.first != -1) { walletInfo.second->deref(); // check if the wallet should be closed now. internalClose(walletInfo.second, walletInfo.first, false); } return -1; } else { if (walletInfo.first != -1) { _sessions.addSession(appid, service, rc); } else { // wallet was forcefully closed. return -1; } } } return rc; } bool KWalletD::isAuthorizedApp( const QString& appid, const QString& wallet, WId w) { if (!_openPrompt) { return true; } int response = 0; QString thisApp; if (appid.isEmpty()) { thisApp = QStringLiteral("KDE System"); } else { thisApp = appid; } if (!implicitAllow(wallet, thisApp)) { KConfigGroup cfg = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Allow"); if (!cfg.isEntryImmutable(wallet)) { KBetterThanKDialog* dialog = new KBetterThanKDialog; dialog->setWindowTitle(i18n("KDE Wallet Service")); if (appid.isEmpty()) { dialog->setLabel(i18n("KDE has requested access to the " "open wallet '%1'.", wallet.toHtmlEscaped())); } else { dialog->setLabel( i18n("The application '%1' has requested " "access to the open wallet '%2'.", appid.toHtmlEscaped(), wallet.toHtmlEscaped())); } setupDialog(dialog, w, appid, false); response = dialog->exec(); delete dialog; } } if (response == 0 || response == 1) { if (response == 1) { KConfigGroup cfg = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Allow"); QStringList apps = cfg.readEntry(wallet, QStringList()); if (!apps.contains(thisApp)) { if (cfg.isEntryImmutable(wallet)) { return false; } apps += thisApp; _implicitAllowMap[wallet] += thisApp; cfg.writeEntry(wallet, apps); cfg.sync(); } } } else if (response == 3) { KConfigGroup cfg = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Deny"); QStringList apps = cfg.readEntry(wallet, QStringList()); if (!apps.contains(thisApp)) { apps += thisApp; _implicitDenyMap[wallet] += thisApp; cfg.writeEntry(wallet, apps); cfg.sync(); } return false; } else { return false; } return true; } int KWalletD::deleteWallet(const QString& wallet) { int result = -1; QString path = KWallet::Backend::getSaveLocation() + "/" + wallet + ".kwl"; QString pathSalt = KWallet::Backend::getSaveLocation() + "/" + wallet + ".salt"; if (QFile::exists(path)) { const QPair walletInfo = findWallet(wallet); internalClose(walletInfo.second, walletInfo.first, true); QFile::remove(path); emit walletDeleted(wallet); // also delete access control entries KConfigGroup cfgAllow = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Allow"); cfgAllow.deleteEntry(wallet); KConfigGroup cfgDeny = KSharedConfig::openConfig(QStringLiteral("kwalletrc"))->group("Auto Deny"); cfgDeny.deleteEntry(wallet); if (QFile::exists(pathSalt)) { QFile::remove(pathSalt); } result = 0; } return result; } void KWalletD::changePassword( const QString& wallet, qlonglong wId, const QString& appid) { KWalletTransaction* xact = new KWalletTransaction(connection()); message().setDelayedReply(true); xact->message = message(); // TODO GPG this shouldn't be allowed on a GPG managed wallet; a warning // should be displayed about this xact->appid = appid; xact->wallet = wallet; xact->wId = wId; xact->modal = false; xact->tType = KWalletTransaction::ChangePassword; _transactions.append(xact); QTimer::singleShot(0, this, SLOT(processTransactions())); checkActiveDialog(); checkActiveDialog(); } void KWalletD::initiateSync(int handle) { // add a timer and reset it right away _syncTimers.addTimer(handle, _syncTime); _syncTimers.resetTimer(handle, _syncTime); } void KWalletD::doTransactionChangePassword( const QString& appid, const QString& wallet, qlonglong wId) { const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* w = walletInfo.second; bool reclose = false; if (!w) { handle = doTransactionOpen(appid, wallet, false, wId, false, QLatin1String("")); if (-1 == handle) { KMessageBox::sorryWId((WId)wId, i18n("Unable to open wallet. The wallet must be opened in " "order to change the password."), i18n("KDE Wallet Service")); return; } w = _wallets.value(handle); reclose = true; } assert(w); #ifdef HAVE_GPGMEPP if (w->cipherType() == KWallet::BACKEND_CIPHER_GPG) { QString keyID = w->gpgKey().shortKeyID(); assert(!keyID.isNull()); KMessageBox::errorWId( (WId)wId, i18n("The %1 wallet is encrypted using GPG " "key %2. Please use GPG tools (such " "as kleopatra) to change the passphrase " "associated to that key.", wallet.toHtmlEscaped(), keyID)); } else { #endif QPointer kpd = new KNewPasswordDialog(); kpd->setPrompt(i18n("Please choose a new password for the wallet " "'%1'.", wallet.toHtmlEscaped())); kpd->setWindowTitle(i18n("KDE Wallet Service")); kpd->setAllowEmptyPasswords(true); KColorScheme colorScheme(QPalette::Active, KColorScheme::View); kpd->setBackgroundWarningColor(colorScheme.background(KColorScheme::NegativeBackground).color()); setupDialog(kpd, (WId)wId, appid, false); if (kpd->exec() == QDialog::Accepted && kpd) { QString p = kpd->password(); if (!p.isNull()) { w->setPassword(p.toUtf8()); int rc = w->close(true); if (rc < 0) { KMessageBox::sorryWId((WId)wId, i18n("Error re-encrypting the wallet. Password was " "not changed."), i18n("KDE Wallet Service")); reclose = true; } else { rc = w->open(p.toUtf8()); if (rc < 0) { KMessageBox::sorryWId((WId)wId, i18n("Error reopening the wallet. Data may be " "lost."), i18n("KDE Wallet Service")); reclose = true; } } } } delete kpd; #ifdef HAVE_GPGMEPP } #endif if (reclose) { internalClose(w, handle, true); } } int KWalletD::close(const QString& wallet, bool force) { const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* w = walletInfo.second; return internalClose(w, handle, force); } int KWalletD::internalClose(KWallet::Backend* const w, const int handle, const bool force, const bool saveBeforeClose) { if (w) { const QString& wallet = w->walletName(); if ((w->refCount() == 0 && !_leaveOpen) || force) { // this is only a safety measure. sessions should be gone already. _sessions.removeAllSessions(handle); if (_closeIdle) { _closeTimers.removeTimer(handle); } _syncTimers.removeTimer(handle); _wallets.remove(handle); w->close(saveBeforeClose); doCloseSignals(handle, wallet); delete w; return 0; } return 1; } return -1; } int KWalletD::close(int handle, bool force, const QString& appid) { KWallet::Backend* w = _wallets.value(handle); if (w) { if (_sessions.hasSession(appid, handle)) { // remove one handle for the application bool removed = _sessions.removeSession(appid, message().service(), handle); // alternatively try sessionless if (removed || _sessions.removeSession(appid, QLatin1String(""), handle)) { w->deref(); } return internalClose(w, handle, force); } return 1; // not closed, handle unknown } return -1; // not open to begin with, or other error } bool KWalletD::isOpen(const QString& wallet) { const QPair walletInfo = findWallet(wallet); return walletInfo.second != nullptr; } bool KWalletD::isOpen(int handle) { if (handle == 0) { return false; } KWallet::Backend* rc = _wallets.value(handle); if (rc == nullptr && ++_failed > 5) { _failed = 0; QTimer::singleShot(0, this, SLOT(notifyFailures())); } else if (rc != nullptr) { _failed = 0; } return rc != nullptr; } QStringList KWalletD::wallets() const { QString path = KWallet::Backend::getSaveLocation(); QDir dir(path, QStringLiteral("*.kwl")); QStringList rc; dir.setFilter(QDir::Files | QDir::Hidden); const auto list = dir.entryInfoList(); for (const QFileInfo& fi : list) { QString fn = fi.fileName(); if (fn.endsWith(QLatin1String(".kwl"))) { fn.truncate(fn.length() - 4); } rc += fn; } return rc; } void KWalletD::sync(int handle, const QString& appid) { KWallet::Backend* b; // get the wallet and check if we have a password for it (safety measure) if ((b = getWallet(appid, handle))) { QString wallet = b->walletName(); b->sync(0); } } void KWalletD::timedOutSync(int handle) { _syncTimers.removeTimer(handle); if (_wallets.contains(handle) && _wallets[handle]) { _wallets[handle]->sync(0); } else { qDebug("wallet not found for sync!"); } } void KWalletD::doTransactionOpenCancelled( const QString& appid, const QString& wallet, const QString& service) { // there will only be one session left to remove - all others // have already been removed in slotServiceOwnerChanged and all // transactions for opening new sessions have been deleted. if (!_sessions.hasSession(appid)) { return; } const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* b = walletInfo.second; if (handle != -1 && b) { b->deref(); internalClose(b, handle, false); } // close the session in case the wallet hasn't been closed yet _sessions.removeSession(appid, service, handle); } QStringList KWalletD::folderList(int handle, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { return b->folderList(); } return QStringList(); } bool KWalletD::hasFolder(int handle, const QString& f, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { return b->hasFolder(f); } return false; } bool KWalletD::removeFolder( int handle, const QString& f, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { bool rc = b->removeFolder(f); initiateSync(handle); emit folderListUpdated(b->walletName()); return rc; } return false; } bool KWalletD::createFolder( int handle, const QString& f, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { bool rc = b->createFolder(f); initiateSync(handle); emit folderListUpdated(b->walletName()); return rc; } return false; } QByteArray KWalletD::readMap(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry* e = b->readEntry(key); if (e && e->type() == KWallet::Wallet::Map) { return e->map(); } } return QByteArray(); } +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) QVariantMap KWalletD::readMapList(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); QVariantMap rc; const auto lst = b->readEntryList(key); for (KWallet::Entry* entry : lst) { if (entry->type() == KWallet::Wallet::Map) { rc.insert(entry->key(), entry->map()); } } return rc; } return QVariantMap(); } +#endif + +QVariantMap KWalletD::mapList(int handle, const QString &folder, const QString &appid) +{ + QVariantMap rc; + + KWallet::Backend *backend = getWallet(appid, handle); + if (backend) { + backend->setFolder(folder); + const QList lst = backend->entriesList(); + for (KWallet::Entry *entry : lst) { + if (entry->type() == KWallet::Wallet::Map) { + rc.insert(entry->key(), entry->map()); + } + } + } + + return rc; +} QByteArray KWalletD::readEntry(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry* e = b->readEntry(key); if (e) { return e->value(); } } return QByteArray(); } +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) QVariantMap KWalletD::readEntryList(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); QVariantMap rc; const auto lst = b->readEntryList(key); for (KWallet::Entry* entry : lst) { rc.insert(entry->key(), entry->value()); } return rc; } return QVariantMap(); } +#endif + +QVariantMap KWalletD::entriesList(int handle, const QString &folder, const QString &appid) +{ + + QVariantMap rc; + + KWallet::Backend *backend = getWallet(appid, handle); + if (backend) { + backend->setFolder(folder); + const QList lst = backend->entriesList(); + for (KWallet::Entry *entry : lst) { + rc.insert(entry->key(), entry->value()); + } + } + + return rc; +} QStringList KWalletD::entryList( int handle, const QString& folder, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); return b->entryList(); } return QStringList(); } QString KWalletD::readPassword(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry* e = b->readEntry(key); if (e && e->type() == KWallet::Wallet::Password) { return e->password(); } } return QString(); } +#if KWALLET_BUILD_DEPRECATED_SINCE(5, 70) QVariantMap KWalletD::readPasswordList(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); QVariantMap rc; const auto lst = b->readEntryList(key); for (KWallet::Entry* entry : lst) { if (entry->type() == KWallet::Wallet::Password) { rc.insert(entry->key(), entry->password()); } } return rc; } return QVariantMap(); } +#endif + +QVariantMap KWalletD::passwordList(int handle, const QString &folder, const QString &appid) +{ + QVariantMap rc; + + KWallet::Backend *backend = getWallet(appid, handle); + if (backend) { + backend->setFolder(folder); + const QList lst = backend->entriesList(); + for (KWallet::Entry *entry : lst) { + if (entry->type() == KWallet::Wallet::Password) { + rc.insert(entry->key(), entry->password()); + } + } + } + + return rc; +} int KWalletD::writeMap(int handle, const QString& folder, const QString& key, const QByteArray& value, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::Map); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::writeEntry(int handle, const QString& folder, const QString& key, const QByteArray& value, int entryType, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::EntryType(entryType)); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::writeEntry(int handle, const QString& folder, const QString& key, const QByteArray& value, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::Stream); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::writePassword(int handle, const QString& folder, const QString& key, const QString& value, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); KWallet::Entry e; e.setKey(key); e.setValue(value); e.setType(KWallet::Wallet::Password); b->writeEntry(&e); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return 0; } return -1; } int KWalletD::entryType(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { if (!b->hasFolder(folder)) { return KWallet::Wallet::Unknown; } b->setFolder(folder); if (b->hasEntry(key)) { return b->readEntry(key)->type(); } } return KWallet::Wallet::Unknown; } bool KWalletD::hasEntry(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { if (!b->hasFolder(folder)) { return false; } b->setFolder(folder); return b->hasEntry(key); } return false; } int KWalletD::removeEntry(int handle, const QString& folder, const QString& key, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { if (!b->hasFolder(folder)) { return 0; } b->setFolder(folder); bool rc = b->removeEntry(key); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return rc ? 0 : -3; } return -1; } void KWalletD::slotServiceOwnerChanged( const QString& name, const QString& oldOwner, const QString& newOwner) { Q_UNUSED(name); qCDebug(KWALLETD_LOG) << "slotServiceOwnerChanged " << name << ", " << oldOwner << ", " << newOwner; if (!newOwner.isEmpty()) { return; // no application exit, don't care. } // as we don't have the application id we have to cycle // all sessions. As an application can basically open wallets // with several appids, we can't stop if we found one. QString service(oldOwner); const QList sessremove(_sessions.findSessions(service)); KWallet::Backend* b = nullptr; // check all sessions for wallets to close for (const KWalletAppHandlePair& s : sessremove) { b = getWallet(s.first, s.second); if (b) { b->deref(); internalClose(b, s.second, false); } } // remove all the sessions in case they aren't gone yet for (const KWalletAppHandlePair& s : sessremove) { _sessions.removeSession(s.first, service, s.second); } // cancel all open-transactions still running for the service QList::iterator tit; for (tit = _transactions.begin(); tit != _transactions.end(); ++tit) { if ((*tit)->tType == KWalletTransaction::Open && (*tit)->service == oldOwner) { delete (*tit); *tit = nullptr; } } _transactions.removeAll(nullptr); // if there's currently an open-transaction being handled, // mark it as cancelled. if (_curtrans && _curtrans->tType == KWalletTransaction::Open && _curtrans->service == oldOwner) { qCDebug(KWALLETD_LOG) << "Cancelling current transaction!"; _curtrans->cancelled = true; } _serviceWatcher.removeWatchedService(oldOwner); } KWallet::Backend* KWalletD::getWallet(const QString& appid, int handle) { if (handle == 0) { return nullptr; } KWallet::Backend* w = _wallets.value(handle); if (w) { // the handle is valid if (_sessions.hasSession(appid, handle)) { // the app owns this handle _failed = 0; if (_closeIdle) { _closeTimers.resetTimer(handle, _idleTime); } return w; } } if (++_failed > 5) { _failed = 0; QTimer::singleShot(0, this, SLOT(notifyFailures())); } return nullptr; } void KWalletD::notifyFailures() { if (!_showingFailureNotify) { _showingFailureNotify = true; KMessageBox::information(nullptr, i18n("There have been repeated failed attempts to gain access to " "a wallet. An application may be misbehaving."), i18n("KDE Wallet Service")); _showingFailureNotify = false; } } void KWalletD::doCloseSignals(int handle, const QString& wallet) { emit walletClosed(handle); emit walletClosed(wallet); if (_wallets.isEmpty()) { emit allWalletsClosed(); } } int KWalletD::renameEntry(int handle, const QString& folder, const QString& oldName, const QString& newName, const QString& appid) { KWallet::Backend* b; if ((b = getWallet(appid, handle))) { b->setFolder(folder); int rc = b->renameEntry(oldName, newName); initiateSync(handle); emitFolderUpdated(b->walletName(), folder); return rc; } return -1; } QStringList KWalletD::users(const QString& wallet) const { const QPair walletInfo = findWallet(wallet); return _sessions.getApplications(walletInfo.first); } bool KWalletD::disconnectApplication( const QString& wallet, const QString& application) { const QPair walletInfo = findWallet(wallet); int handle = walletInfo.first; KWallet::Backend* backend = walletInfo.second; if (handle != -1 && _sessions.hasSession(application, handle)) { int removed = _sessions.removeAllSessions(application, handle); for (int i = 0; i < removed; ++i) { backend->deref(); } internalClose(backend, handle, false); emit applicationDisconnected(wallet, application); return true; } return false; } void KWalletD::emitFolderUpdated(const QString& wallet, const QString& folder) { emit folderUpdated(wallet, folder); } void KWalletD::emitWalletListDirty() { const QStringList walletsInDisk = wallets(); const auto lst = _wallets.values(); for (auto i : lst) { if (!walletsInDisk.contains(i->walletName())) { internalClose(i, _wallets.key(i), true, false); } } emit walletListDirty(); } void KWalletD::reconfigure() { KConfig cfg(QStringLiteral("kwalletrc")); KConfigGroup walletGroup(&cfg, "Wallet"); _firstUse = walletGroup.readEntry("First Use", true); _enabled = walletGroup.readEntry("Enabled", true); _launchManager = walletGroup.readEntry("Launch Manager", false); _leaveOpen = walletGroup.readEntry("Leave Open", true); bool idleSave = _closeIdle; _closeIdle = walletGroup.readEntry("Close When Idle", false); _openPrompt = walletGroup.readEntry("Prompt on Open", false); int timeSave = _idleTime; // in minutes! _idleTime = walletGroup.readEntry("Idle Timeout", 10) * 60 * 1000; #ifdef Q_WS_X11 if (walletGroup.readEntry("Close on Screensaver", false)) { // BUG 254273 : if kwalletd starts before the screen saver, then the // connection fails and kwalletd never receives it's notifications // To fix this, we use a timer and perform periodic connection // attempts until connection succeeds QTimer::singleShot(0, this, SLOT(connectToScreenSaver())); } else { if (screensaver && screensaver->isValid()) { screensaver->disconnect(SIGNAL(ActiveChanged(bool)), this, SLOT(screenSaverChanged(bool))); delete screensaver; screensaver = 0; } } #endif // Handle idle changes if (_closeIdle) { if (_idleTime != timeSave) { // Timer length changed Wallets::const_iterator it = _wallets.constBegin(); const Wallets::const_iterator end = _wallets.constEnd(); for (; it != end; ++it) { _closeTimers.resetTimer(it.key(), _idleTime); } } if (!idleSave) { // add timers for all the wallets Wallets::const_iterator it = _wallets.constBegin(); const Wallets::const_iterator end = _wallets.constEnd(); for (; it != end; ++it) { _closeTimers.addTimer(it.key(), _idleTime); } } } else { _closeTimers.clear(); } // Update the implicit allow stuff _implicitAllowMap.clear(); const KConfigGroup autoAllowGroup(&cfg, "Auto Allow"); QStringList entries = autoAllowGroup.entryMap().keys(); for (QStringList::const_iterator i = entries.constBegin(); i != entries.constEnd(); ++i) { _implicitAllowMap[*i] = autoAllowGroup.readEntry(*i, QStringList()); } // Update the implicit allow stuff _implicitDenyMap.clear(); const KConfigGroup autoDenyGroup(&cfg, "Auto Deny"); entries = autoDenyGroup.entryMap().keys(); for (QStringList::const_iterator i = entries.constBegin(); i != entries.constEnd(); ++i) { _implicitDenyMap[*i] = autoDenyGroup.readEntry(*i, QStringList()); } // Update if wallet was enabled/disabled if (!_enabled) { // close all wallets while (!_wallets.isEmpty()) { Wallets::const_iterator it = _wallets.constBegin(); internalClose(it.value(), it.key(), true); } QApplication::exit(0); } } bool KWalletD::isEnabled() const { return _enabled; } bool KWalletD::folderDoesNotExist( const QString& wallet, const QString& folder) { if (!wallets().contains(wallet)) { return true; } const QPair walletInfo = findWallet(wallet); if (walletInfo.second) { return walletInfo.second->folderDoesNotExist(folder); } KWallet::Backend* b = new KWallet::Backend(wallet); b->open(QByteArray()); bool rc = b->folderDoesNotExist(folder); delete b; return rc; } bool KWalletD::keyDoesNotExist( const QString& wallet, const QString& folder, const QString& key) { if (!wallets().contains(wallet)) { return true; } const QPair walletInfo = findWallet(wallet); if (walletInfo.second) { return walletInfo.second->entryDoesNotExist(folder, key); } KWallet::Backend* b = new KWallet::Backend(wallet); b->open(QByteArray()); bool rc = b->entryDoesNotExist(folder, key); delete b; return rc; } bool KWalletD::implicitAllow(const QString& wallet, const QString& app) { return _implicitAllowMap[wallet].contains(app); } bool KWalletD::implicitDeny(const QString& wallet, const QString& app) { return _implicitDenyMap[wallet].contains(app); } void KWalletD::timedOutClose(int id) { KWallet::Backend* w = _wallets.value(id); if (w) { internalClose(w, id, true); } } void KWalletD::closeAllWallets() { Wallets walletsCopy = _wallets; Wallets::const_iterator it = walletsCopy.constBegin(); const Wallets::const_iterator end = walletsCopy.constEnd(); for (; it != end; ++it) { internalClose(it.value(), it.key(), true); } walletsCopy.clear(); // All of this should be basically noop. Let's just be safe. _wallets.clear(); } QString KWalletD::networkWallet() { return KWallet::Wallet::NetworkWallet(); } QString KWalletD::localWallet() { return KWallet::Wallet::LocalWallet(); } void KWalletD::screenSaverChanged(bool s) { if (s) { closeAllWallets(); } } void KWalletD::activatePasswordDialog() { checkActiveDialog(); } int KWalletD::pamOpen( const QString& wallet, const QByteArray& passwordHash, int sessionTimeout) { if (_processing) { return -1; } if (!walletRegex.match(wallet).hasMatch()) { return -1; } // check if the wallet is already open QPair walletInfo = findWallet(wallet); int rc = walletInfo.first; if (rc != -1) { return rc; // Wallet already opened, return handle } if (_wallets.count() > 20) { return -1; } KWallet::Backend* b = nullptr; // If the wallet we want to open does not exists. create it and set pam // hash if (!wallets().contains(wallet)) { b = new KWallet::Backend(wallet); b->setCipherType(KWallet::BACKEND_CIPHER_BLOWFISH); } else { b = new KWallet::Backend(wallet); } int openrc = b->openPreHashed(passwordHash); if (openrc != 0 || !b->isOpen()) { delete b; return openrc; } // opening the wallet was successful int handle = generateHandle(); _wallets.insert(handle, b); _syncTimers.addTimer(handle, _syncTime); // don't reference the wallet or add a session so it // can be reclosed easily. if (sessionTimeout > 0) { _closeTimers.addTimer(handle, sessionTimeout); } else if (_closeIdle) { _closeTimers.addTimer(handle, _idleTime); } emit walletOpened(wallet); if (_wallets.count() == 1 && _launchManager) { KToolInvocation::startServiceByDesktopName(QStringLiteral("kwalletmanager5-kwalletd")); } return handle; } // vim: tw=220:ts=4 diff --git a/src/runtime/kwalletd/kwalletd.h b/src/runtime/kwalletd/kwalletd.h index 3f0d6c7..9bf2807 100644 --- a/src/runtime/kwalletd/kwalletd.h +++ b/src/runtime/kwalletd/kwalletd.h @@ -1,250 +1,260 @@ /* This file is part of the KDE libraries Copyright (c) 2002-2004 George Staikos Copyright (c) 2008 Michael Leupold This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KWALLETD_H_ #define _KWALLETD_H_ #include #include #include "kwalletbackend.h" #include #include #include #include #include #include "ktimeout.h" #include "kwalletsessionstore.h" class KDirWatch; class KTimeout; // @Private class KWalletTransaction; class KWalletSessionStore; class KWalletD : public QObject, protected QDBusContext { Q_OBJECT public: KWalletD(); ~KWalletD() override; public Q_SLOTS: // Is the wallet enabled? If not, all open() calls fail. bool isEnabled() const; // Open and unlock the wallet int open(const QString &wallet, qlonglong wId, const QString &appid); // Open and unlock the wallet with this path int openPath(const QString &path, qlonglong wId, const QString &appid); // Open the wallet asynchronously int openAsync(const QString &wallet, qlonglong wId, const QString &appid, bool handleSession); // Open and unlock the wallet with this path asynchronously int openPathAsync(const QString &path, qlonglong wId, const QString &appid, bool handleSession); // Close and lock the wallet // If force = true, will close it for all users. Behave. This // can break applications, and is generally intended for use by // the wallet manager app only. int close(const QString &wallet, bool force); int close(int handle, bool force, const QString &appid); // Save to disk but leave open Q_NOREPLY void sync(int handle, const QString &appid); // Physically deletes the wallet from disk. int deleteWallet(const QString &wallet); // Returns true if the wallet is open bool isOpen(const QString &wallet); bool isOpen(int handle); // List the users of this wallet QStringList users(const QString &wallet) const; // Change the password of this wallet void changePassword(const QString &wallet, qlonglong wId, const QString &appid); // A list of all wallets QStringList wallets() const; // A list of all folders in this wallet QStringList folderList(int handle, const QString &appid); // Does this wallet have this folder? bool hasFolder(int handle, const QString &folder, const QString &appid); // Create this folder bool createFolder(int handle, const QString &folder, const QString &appid); // Remove this folder bool removeFolder(int handle, const QString &folder, const QString &appid); // List of entries in this folder QStringList entryList(int handle, const QString &folder, const QString &appid); // Read an entry. If the entry does not exist, it just // returns an empty result. It is your responsibility to check // hasEntry() first. QByteArray readEntry(int handle, const QString &folder, const QString &key, const QString &appid); QByteArray readMap(int handle, const QString &folder, const QString &key, const QString &appid); QString readPassword(int handle, const QString &folder, const QString &key, const QString &appid); + +#if KWALLET_ENABLE_DEPRECATED_SINCE(5, 70) + // use entriesList() QVariantMap readEntryList(int handle, const QString &folder, const QString &key, const QString &appid); + // use mapList() QVariantMap readMapList(int handle, const QString &folder, const QString &key, const QString &appid); + // use passwordList() QVariantMap readPasswordList(int handle, const QString &folder, const QString &key, const QString &appid); +#endif + + QVariantMap entriesList(int handle, const QString &folder, const QString &appid); + QVariantMap mapList(int handle, const QString &folder, const QString &appid); + QVariantMap passwordList(int handle, const QString &folder, const QString &appid); // Rename an entry. rc=0 on success. int renameEntry(int handle, const QString &folder, const QString &oldName, const QString &newName, const QString &appid); // Write an entry. rc=0 on success. int writeEntry(int handle, const QString &folder, const QString &key, const QByteArray &value, int entryType, const QString &appid); int writeEntry(int handle, const QString &folder, const QString &key, const QByteArray &value, const QString &appid); int writeMap(int handle, const QString &folder, const QString &key, const QByteArray &value, const QString &appid); int writePassword(int handle, const QString &folder, const QString &key, const QString &value, const QString &appid); // Does the entry exist? bool hasEntry(int handle, const QString &folder, const QString &key, const QString &appid); // What type is the entry? int entryType(int handle, const QString &folder, const QString &key, const QString &appid); // Remove an entry. rc=0 on success. int removeEntry(int handle, const QString &folder, const QString &key, const QString &appid); // Disconnect an app from a wallet bool disconnectApplication(const QString &wallet, const QString &application); void reconfigure(); // Determine bool folderDoesNotExist(const QString &wallet, const QString &folder); bool keyDoesNotExist(const QString &wallet, const QString &folder, const QString &key); void closeAllWallets(); QString networkWallet(); QString localWallet(); void screenSaverChanged(bool); // Open a wallet using a pre-hashed password. This is only useful in cooperation // with the kwallet PAM module. It's also less secure than manually entering the // password as the password hash is transmitted using D-Bus. int pamOpen(const QString &wallet, const QByteArray &passwordHash, int sessionTimeout); Q_SIGNALS: void walletAsyncOpened(int id, int handle); // used to notify KWallet::Wallet void walletListDirty(); void walletCreated(const QString &wallet); void walletOpened(const QString &wallet); void walletDeleted(const QString &wallet); void walletClosed(const QString &wallet); void walletClosed(int handle); void allWalletsClosed(); void folderListUpdated(const QString &wallet); void folderUpdated(const QString &, const QString &); void applicationDisconnected(const QString &wallet, const QString &application); private Q_SLOTS: void slotServiceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner); void emitWalletListDirty(); void timedOutClose(int handle); void timedOutSync(int handle); void notifyFailures(); void processTransactions(); void activatePasswordDialog(); void registerKWalletd4Service(); #ifdef Q_WS_X11 void connectToScreenSaver(); #endif private: // Internal - open a wallet int internalOpen(const QString &appid, const QString &wallet, bool isPath, WId w, bool modal, const QString &service); // Internal - close this wallet. int internalClose(KWallet::Backend * const w, const int handle, const bool force, const bool saveBeforeClose = true); bool isAuthorizedApp(const QString &appid, const QString &wallet, WId w); // This also validates the handle. May return NULL. KWallet::Backend *getWallet(const QString &appid, int handle); // Generate a new unique handle. int generateHandle(); // Emit signals about closing wallets void doCloseSignals(int, const QString &); void emitFolderUpdated(const QString &, const QString &); // Implicitly allow access for this application bool implicitAllow(const QString &wallet, const QString &app); bool implicitDeny(const QString &wallet, const QString &app); void doTransactionChangePassword(const QString &appid, const QString &wallet, qlonglong wId); void doTransactionOpenCancelled(const QString &appid, const QString &wallet, const QString &service); int doTransactionOpen(const QString &appid, const QString &wallet, bool isPath, qlonglong wId, bool modal, const QString &service); void initiateSync(int handle); void setupDialog(QWidget *dialog, WId wId, const QString &appid, bool modal); void checkActiveDialog(); QPair findWallet(const QString &walletName) const; typedef QHash Wallets; Wallets _wallets; KDirWatch *_dw; int _failed; // configuration values bool _leaveOpen, _closeIdle, _launchManager, _enabled; bool _openPrompt, _firstUse, _showingFailureNotify; int _idleTime; QMap _implicitAllowMap, _implicitDenyMap; KTimeout _closeTimers; KTimeout _syncTimers; const int _syncTime; static bool _processing; KWalletTransaction *_curtrans; // current transaction QList _transactions; QPointer< QWidget > activeDialog; #ifdef Q_WS_X11 QDBusInterface *screensaver; #endif // sessions KWalletSessionStore _sessions; QDBusServiceWatcher _serviceWatcher; bool _useGpg; }; #endif