QGIS API Documentation 4.1.0-Master (009143bf4b4)
Loading...
Searching...
No Matches
qgsauthmanager.h
Go to the documentation of this file.
1/***************************************************************************
2 qgsauthmanager.h
3 ---------------------
4 begin : October 5, 2014
5 copyright : (C) 2014 by Boundless Spatial, Inc. USA
6 author : Larry Shaffer
7 email : lshaffer at boundlessgeo dot com
8 ***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17#ifndef QGSAUTHMANAGER_H
18#define QGSAUTHMANAGER_H
19
20#include "qgis_core.h"
21#include "qgis_sip.h"
22
23#include <QNetworkReply>
24#include <QNetworkRequest>
25#include <QObject>
26#include <QRecursiveMutex>
27#include <QSqlDatabase>
28#include <QSqlError>
29#include <QSqlQuery>
30#include <QStringList>
31
32#ifndef QT_NO_SSL
33#include <QSslCertificate>
34#include <QSslKey>
35#include <QtCrypto>
36#include "qgsauthcertutils.h"
37#endif
38
39#include "qgsauthconfig.h"
40#include "qgsauthmethod.h"
41
42#include <qt6keychain/keychain.h>
43
44#ifndef SIP_RUN
45#ifdef HAVE_AUTH
46namespace QCA
47{
48 class Initializer;
49}
50#endif
51#endif
52class QgsAuthMethod;
54class QgsAuthProvider;
57class QTimer;
61
70class CORE_EXPORT QgsAuthManager : public QObject
71{
72 Q_OBJECT
73
74 public:
77
79
81
83
86 {
87 INFO = 0,
90 };
91 Q_ENUM( MessageLevel )
92
93
102 Q_DECL_DEPRECATED bool init( const QString &pluginPath = QString(), const QString &authDatabasePath = QString() ) SIP_DEPRECATED;
103
114 void setup( const QString &pluginPath = QString(), const QString &authDatabasePath = QString() );
115
123 bool ensureInitialized() const;
124
125 ~QgsAuthManager() override;
126
131 QgsAuthConfigurationStorageRegistry *authConfigurationStorageRegistry() const;
132
138 Q_DECL_DEPRECATED QSqlDatabase authDatabaseConnection() const SIP_DEPRECATED;
139
144 Q_DECL_DEPRECATED const QString authDatabaseConfigTable() const SIP_DEPRECATED { return AUTH_CONFIG_TABLE; }
145
151 const QString methodConfigTableName() const;
152
157 Q_DECL_DEPRECATED const QString authDatabaseServersTable() const SIP_DEPRECATED { return AUTH_SERVERS_TABLE; }
158
159
161 bool isDisabled() const;
162
164 const QString disabledMessage() const;
165
171 Q_DECL_DEPRECATED const QString authenticationDatabasePath() const;
172
176 static bool isFilesystemBasedDatabase( const QString &uri );
177
183 QgsAuthConfigurationStorageDb *defaultDbStorage() const SIP_SKIP;
184
189 const QString authenticationDatabaseUri() const;
190
195 const QString authenticationDatabaseUriStripped() const;
196
204 bool createAndStoreRandomMasterPasswordInKeyChain() SIP_SKIP;
205
211 bool setMasterPassword( bool verify = false );
212
219 bool setMasterPassword( const QString &password, bool verify = false );
220
226 bool verifyMasterPassword( const QString &compare = QString() );
227
229 bool masterPasswordIsSet() const;
230
232 bool masterPasswordHashInDatabase() const;
233
238 void clearMasterPassword() { mMasterPass = QString(); }
239
244 bool masterPasswordSame( const QString &password ) const;
245
255 bool resetMasterPassword( const QString &newpass, const QString &oldpass, bool keepbackup, QString *backuppath SIP_INOUT = nullptr );
256
270 bool resetMasterPasswordUsingStoredPasswordHelper( const QString &newPassword, bool keepBackup, QString *backupPath = nullptr ) SIP_SKIP;
271
276 bool scheduledAuthDatabaseErase() SIP_SKIP { return mScheduledDbErase; }
277
290 void setScheduledAuthDatabaseErase( bool scheduleErase ) SIP_SKIP;
291
300 void setScheduledAuthDatabaseEraseRequestEmitted( bool emitted ) { mScheduledDbEraseRequestEmitted = emitted; }
301
303 QString authManTag() const { return AUTH_MAN_TAG; }
304
306 bool registerCoreAuthMethods();
307
309 QgsAuthMethodConfigsMap availableAuthMethodConfigs( const QString &dataprovider = QString() );
310
312 void updateConfigAuthMethods();
313
318 QgsAuthMethod *configAuthMethod( const QString &authcfg );
319
324 QString configAuthMethodKey( const QString &authcfg ) const;
325
329 QStringList authMethodsKeys( const QString &dataprovider = QString() );
330
335 QgsAuthMethod *authMethod( const QString &authMethodKey );
336
342 const QgsAuthMethodMetadata *authMethodMetadata( const QString &authMethodKey ) SIP_SKIP;
343
349 QgsAuthMethodsMap authMethodsMap( const QString &dataprovider = QString() ) SIP_SKIP;
350
351#ifdef HAVE_GUI
352 SIP_IF_FEATURE( HAVE_GUI )
353
354
359 QWidget *authMethodEditWidget( const QString &authMethodKey, QWidget *parent );
360 SIP_END
361#endif
362
367 QgsAuthMethod::Expansions supportedAuthMethodExpansions( const QString &authcfg );
368
370 const QString uniqueConfigId() const;
371
376 bool configIdUnique( const QString &id ) const;
377
382 static bool hasConfigId( const QString &txt );
383
385 QString configIdRegex() const { return AUTH_CFG_REGEX; }
386
388 QStringList configIds() const;
389
396 bool storeAuthenticationConfig( QgsAuthMethodConfig &mconfig SIP_INOUT, bool overwrite = false );
397
403 bool updateAuthenticationConfig( const QgsAuthMethodConfig &config );
404
412 bool loadAuthenticationConfig( const QString &authcfg, QgsAuthMethodConfig &mconfig SIP_INOUT, bool full = false );
413
419 bool removeAuthenticationConfig( const QString &authcfg );
420
428 bool exportAuthenticationConfigsToXml( const QString &filename, const QStringList &authcfgs, const QString &password = QString() );
429
437 bool importAuthenticationConfigsFromXml( const QString &filename, const QString &password = QString(), bool overwrite = false );
438
443 bool removeAllAuthenticationConfigs();
444
449 bool backupAuthenticationDatabase( QString *backuppath SIP_INOUT = nullptr );
450
457 bool eraseAuthenticationDatabase( bool backup, QString *backuppath SIP_INOUT = nullptr );
458
459
461
469 bool updateNetworkRequest( QNetworkRequest &request SIP_INOUT, const QString &authcfg, const QString &dataprovider = QString() );
470
478 bool updateNetworkReply( QNetworkReply *reply, const QString &authcfg, const QString &dataprovider = QString() );
479
487 bool updateDataSourceUriItems( QStringList &connectionItems SIP_INOUT, const QString &authcfg, const QString &dataprovider = QString() );
488
496 bool updateNetworkProxy( QNetworkProxy &proxy SIP_INOUT, const QString &authcfg, const QString &dataprovider = QString() );
497
499
507 bool storeAuthSetting( const QString &key, const QVariant &value, bool encrypt = false );
508
521 QVariant authSetting( const QString &key, const QVariant &defaultValue = QVariant(), bool decrypt = false );
522
524 bool existsAuthSetting( const QString &key );
525
527 bool removeAuthSetting( const QString &key );
528
529#ifndef QT_NO_SSL
531
533 bool initSslCaches();
534
536 bool storeCertIdentity( const QSslCertificate &cert, const QSslKey &key );
537
543 const QSslCertificate certIdentity( const QString &id );
544
551 const QPair<QSslCertificate, QSslKey> certIdentityBundle( const QString &id ) SIP_SKIP;
552
558 const QStringList certIdentityBundleToPem( const QString &id );
559
564 const QList<QSslCertificate> certIdentities();
565
567
572 QStringList certIdentityIds() const;
573
575 bool existsCertIdentity( const QString &id );
576
578 bool removeCertIdentity( const QString &id );
579
580
582 bool storeSslCertCustomConfig( const QgsAuthConfigSslServer &config );
583
590 const QgsAuthConfigSslServer sslCertCustomConfig( const QString &id, const QString &hostport );
591
597 const QgsAuthConfigSslServer sslCertCustomConfigByHost( const QString &hostport );
598
603 const QList<QgsAuthConfigSslServer> sslCertCustomConfigs();
604
606 bool existsSslCertCustomConfig( const QString &id, const QString &hostport );
607
609 bool removeSslCertCustomConfig( const QString &id, const QString &hostport );
610
616 QHash<QString, QSet<QSslError::SslError> > ignoredSslErrorCache() SIP_SKIP { return mIgnoredSslErrorsCache; }
617
619 void dumpIgnoredSslErrorsCache_();
620
622 bool updateIgnoredSslErrorsCacheFromConfig( const QgsAuthConfigSslServer &config );
623
625 bool updateIgnoredSslErrorsCache( const QString &shahostport, const QList<QSslError> &errors );
626
628 bool rebuildIgnoredSslErrorCache();
629
630
632 bool storeCertAuthorities( const QList<QSslCertificate> &certs );
633
635 bool storeCertAuthority( const QSslCertificate &cert );
636
638
644 const QSslCertificate certAuthority( const QString &id );
645
647 bool existsCertAuthority( const QSslCertificate &cert );
648
650 bool removeCertAuthority( const QSslCertificate &cert );
651
656 static const QList<QSslCertificate> systemRootCAs();
657
662 const QList<QSslCertificate> extraFileCAs();
663
668 const QList<QSslCertificate> databaseCAs();
669
674 const QMap<QString, QSslCertificate> mappedDatabaseCAs();
675
681 const QMap<QString, QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > caCertsCache() SIP_SKIP { return mCaCertsCache; }
682
684 bool rebuildCaCertsCache();
685
687 bool storeCertTrustPolicy( const QSslCertificate &cert, QgsAuthCertUtils::CertTrustPolicy policy );
688
694 QgsAuthCertUtils::CertTrustPolicy certTrustPolicy( const QSslCertificate &cert );
695
697 bool removeCertTrustPolicies( const QList<QSslCertificate> &certs );
698
700 bool removeCertTrustPolicy( const QSslCertificate &cert );
701
707 QgsAuthCertUtils::CertTrustPolicy certificateTrustPolicy( const QSslCertificate &cert );
708
710 bool setDefaultCertTrustPolicy( QgsAuthCertUtils::CertTrustPolicy policy );
711
713 QgsAuthCertUtils::CertTrustPolicy defaultCertTrustPolicy();
714
719 const QMap<QgsAuthCertUtils::CertTrustPolicy, QStringList > certTrustCache() { return mCertTrustCache; }
720
722 bool rebuildCertTrustCache();
723
729 const QList<QSslCertificate> trustedCaCerts( bool includeinvalid = false );
730
735 const QList<QSslCertificate> untrustedCaCerts( QList<QSslCertificate> trustedCAs = QList<QSslCertificate>() );
736
738 bool rebuildTrustedCaCertsCache();
739
744 const QList<QSslCertificate> trustedCaCertsCache() { return mTrustedCaCertsCache; }
745
750 const QByteArray trustedCaCertsPemText();
751
752#endif
753
758 const QString passwordHelperErrorMessage() SIP_SKIP { return mPasswordHelperErrorMessage; }
759
764 bool passwordHelperDelete() SIP_SKIP;
765
770 static bool passwordHelperEnabled();
771
776 void setPasswordHelperEnabled( bool enabled );
777
782 static bool passwordHelperLoggingEnabled() SIP_SKIP;
783
788 static void setPasswordHelperLoggingEnabled( bool enabled ) SIP_SKIP;
789
794 bool passwordHelperSync();
795
802 bool verifyStoredPasswordHelperPassword() SIP_SKIP;
803
804 // TODO QGIS 5.0 -- remove
805
812
821 static QString passwordHelperDisplayName( bool titleCase = false );
822
824 static const QString AUTH_MAN_TAG;
825
831 QString sqliteDatabasePath() const SIP_SKIP;
832
833 signals:
834
840
846
855 Q_DECL_DEPRECATED void messageOut( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level = QgsAuthManager::INFO ) const SIP_DEPRECATED;
856
865 void messageLog( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level = Qgis::MessageLevel::Info ) const;
866
875 Q_DECL_DEPRECATED void passwordHelperMessageOut( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level = QgsAuthManager::INFO )
877
886 void passwordHelperMessageLog( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level = Qgis::MessageLevel::Info );
887
892 void masterPasswordVerified( bool verified );
893
896
899
900 public slots:
903
905 void clearCachedConfig( const QString &authcfg );
906
907 private slots:
908 void writeToConsole( const QString &message, const QString &tag = QString(), Qgis::MessageLevel level = Qgis::MessageLevel::Info );
909
919 void tryToStartDbErase();
920
921 protected:
927
928
929#ifdef Q_OS_WIN
930 public:
931 explicit QgsAuthManager() SIP_SKIP;
932#else
933 protected:
934 explicit QgsAuthManager() SIP_SKIP;
935#endif
936
937 private:
941 static QString generatePassword();
942
943 bool initPrivate( const QString &pluginPath );
944
946 // Password Helper methods
947
949 QString passwordHelperName() const;
950
952 void passwordHelperLog( const QString &msg ) const;
953
955 QString passwordHelperRead( bool &ok );
956
958 bool passwordHelperWrite( const QString &password );
959
961 void passwordHelperSetErrorMessage( const QString &errorMessage ) { mPasswordHelperErrorMessage = errorMessage; }
962
964 void passwordHelperClearErrors();
965
970 void passwordHelperProcessError();
971
972 bool masterPasswordInput();
973
980 bool masterPasswordRowsInDb( int &rows ) const;
981
982 bool masterPasswordCheckAgainstDb( const QString &compare = QString() ) const;
983
984 bool masterPasswordStoreInDb() const;
985
986 bool masterPasswordClearDb();
987
988 const QString masterPasswordCiv() const;
989
990 bool verifyPasswordCanDecryptConfigs() const;
991
992 bool reencryptAllAuthenticationConfigs( const QString &prevpass, const QString &prevciv );
993
994 bool reencryptAuthenticationConfig( const QString &authcfg, const QString &prevpass, const QString &prevciv );
995
996 bool reencryptAllAuthenticationSettings( const QString &prevpass, const QString &prevciv );
997
998 bool reencryptAllAuthenticationIdentities( const QString &prevpass, const QString &prevciv );
999
1000 bool reencryptAuthenticationIdentity( const QString &identid, const QString &prevpass, const QString &prevciv );
1001
1002#ifndef QT_NO_SSL
1003 void insertCaCertInCache( QgsAuthCertUtils::CaCertSource source, const QList<QSslCertificate> &certs );
1004#endif
1005
1006 QString authPasswordHelperKeyName() const;
1007
1011 QgsAuthConfigurationStorage *firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability capability ) const;
1012
1013 static QgsAuthManager *sInstance;
1014 static const QString AUTH_CONFIG_TABLE;
1015 static const QString AUTH_SERVERS_TABLE;
1016 static const QString AUTH_CFG_REGEX;
1017
1018 QString mPluginPath;
1019 QString mAuthDatabaseConnectionUri;
1020
1021 mutable bool mLazyInitResult = false;
1022 bool mAuthInit = false;
1023
1024 mutable std::unique_ptr<QgsAuthConfigurationStorageRegistry> mAuthConfigurationStorageRegistry;
1025#ifdef HAVE_AUTH
1026 std::unique_ptr<QCA::Initializer> mQcaInitializer;
1027#endif
1028
1029 QHash<QString, QString> mConfigAuthMethods;
1030 QHash<QString, QgsAuthMethod *> mAuthMethods;
1031
1032 QString mMasterPass;
1033 int mPassTries = 0;
1034 bool mAuthDisabled = false;
1035 QString mAuthDisabledMessage;
1036 std::unique_ptr<QTimer> mScheduledDbEraseTimer;
1037 bool mScheduledDbErase = false;
1038 int mScheduledDbEraseRequestWait = 3; // in seconds
1039 bool mScheduledDbEraseRequestEmitted = false;
1040 int mScheduledDbEraseRequestCount = 0;
1041
1042 std::unique_ptr<QRecursiveMutex> mMutex;
1043 std::unique_ptr<QRecursiveMutex> mMasterPasswordMutex;
1044#ifndef QT_NO_SSL
1045 // mapping of sha1 digest and cert source and cert
1046 // appending removes duplicates
1047 QMap<QString, QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > mCaCertsCache;
1048 // list of sha1 digests per policy
1049 QMap<QgsAuthCertUtils::CertTrustPolicy, QStringList > mCertTrustCache;
1050 // cache of certs ready to be utilized in network connections
1051 QList<QSslCertificate> mTrustedCaCertsCache;
1052 // cache of SSL errors to be ignored in network connections, per sha-hostport
1053 QHash<QString, QSet<QSslError::SslError> > mIgnoredSslErrorsCache;
1054
1055 bool mHasCustomConfigByHost = false;
1056 bool mHasCheckedIfCustomConfigByHostExists = false;
1057 QMap< QString, QgsAuthConfigSslServer > mCustomConfigByHostCache;
1058#endif
1059
1061 // Password Helper Variables
1062
1064 bool mPasswordHelperVerificationError = false;
1065
1067 QString mPasswordHelperErrorMessage;
1068
1070 QKeychain::Error mPasswordHelperErrorCode = QKeychain::NoError;
1071
1073 bool mPasswordHelperLoggingEnabled = false;
1074
1076 bool mPasswordHelperFailedInit = false;
1077
1079 static const QLatin1String AUTH_PASSWORD_HELPER_KEY_NAME_BASE;
1080
1082 static const QLatin1String AUTH_PASSWORD_HELPER_FOLDER_NAME;
1083
1084 mutable QMap<QThread *, QMetaObject::Connection> mConnectedThreads;
1085
1086 friend class QgsApplication;
1087};
1088
1089#endif // QGSAUTHMANAGER_H
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:62
AuthConfigurationStorageCapability
Authentication configuration storage capabilities.
Definition qgis.h:107
CertTrustPolicy
Type of certificate trust policy.
CaCertSource
Type of CA certificate source.
Configuration container for SSL server connection exceptions or overrides.
QSqlDatabase based implementation of QgsAuthConfigurationStorage.
Registry for authentication configuration storages.
Abstract class that defines the interface for all authentication configuration storage implementation...
Singleton which offers an interface to manage the authentication configuration database and to utiliz...
void clearAllCachedConfigs()
Clear all authentication configs from authentication method caches.
MessageLevel
Message log level (mirrors that of QgsMessageLog, so it can also output there).
const QList< QSslCertificate > trustedCaCertsCache()
trustedCaCertsCache cache of trusted certificate authorities, ready for network connections
Q_DECL_DEPRECATED void passwordHelperMessageOut(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level=QgsAuthManager::INFO)
Custom logging signal to inform the user about master password <-> password manager interactions.
const QMap< QgsAuthCertUtils::CertTrustPolicy, QStringList > certTrustCache()
certTrustCache get cache of certificate sha1s, per trust policy
bool scheduledAuthDatabaseErase()
Whether there is a scheduled opitonal erase of authentication database.
void passwordHelperMessageLog(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level=Qgis::MessageLevel::Info)
Custom logging signal to inform the user about master password <-> password manager interactions.
QString sqliteDatabasePath() const
Returns the path to the authentication database file or an empty string if the database is not SQLite...
void authDatabaseChanged()
Emitted when the authentication db is significantly changed, e.g. large record removal,...
static const QString AUTH_MAN_TAG
The display name of the Authentication Manager.
friend class QgsApplication
static const QgsSettingsEntryBool * settingsPasswordHelperInsecureFallback
static const QgsSettingsEntryBool * settingsGenerateRandomPasswordForPasswordHelper
Q_DECL_DEPRECATED const QString authDatabaseConfigTable() const
Name of the authentication database table that stores configs.
QString authManTag() const
Simple text tag describing authentication system for message logs.
const QMap< QString, QPair< QgsAuthCertUtils::CaCertSource, QSslCertificate > > caCertsCache()
caCertsCache get all CA certs mapped to their sha1 from cache.
Q_DECL_DEPRECATED void messageOut(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level=QgsAuthManager::INFO) const
Custom logging signal to relay to console output and QgsMessageLog.
void passwordHelperSuccess()
Signals emitted on password helper success, mainly used in the tests to exit main application loop.
QString configIdRegex() const
Returns the regular expression for authcfg=.{7} key/value token for authentication ids.
void messageLog(const QString &message, const QString &tag=QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level=Qgis::MessageLevel::Info) const
Custom logging signal to relay to console output and QgsMessageLog.
void authDatabaseEraseRequested()
Emitted when a user has indicated they may want to erase the authentication db.
void setScheduledAuthDatabaseEraseRequestEmitted(bool emitted)
Re-emit a signal to schedule an optional erase of authentication database.
void passwordHelperFailure()
Signals emitted on password helper failure, mainly used in the tests to exit main application loop.
void clearCachedConfig(const QString &authcfg)
Clear an authentication config from its associated authentication method cache.
void clearMasterPassword()
Clear supplied master password.
const QString passwordHelperErrorMessage()
Error message getter.
static const QgsSettingsEntryBool * settingsPasswordHelperLogging
static const QgsSettingsEntryBool * settingsUsingGeneratedRandomPassword
static QgsAuthManager * instance()
Enforce singleton pattern.
void masterPasswordVerified(bool verified)
Emitted when a password has been verify (or not).
QHash< QString, QSet< QSslError::SslError > > ignoredSslErrorCache()
ignoredSslErrorCache Get ignored SSL error cache, keyed with cert/connection's sha:host:port.
static const QgsSettingsEntryBool * settingsUsePasswordHelper
static const QString AUTH_PASSWORD_HELPER_DISPLAY_NAME
The display name of the password helper (platform dependent).
Q_DECL_DEPRECATED const QString authDatabaseServersTable() const
Name of the authentication database table that stores server exceptions/configs.
static QString passwordHelperDisplayName(bool titleCase=false)
Returns a translated display name of the password helper (platform dependent).
Configuration storage class for authentication method configurations.
Abstract base class for the edit widget of authentication method plugins.
Holds data auth method key, description, and associated shared library file information.
Abstract base class for authentication method plugins.
QFlags< Expansion > Expansions
A boolean settings entry.
#define SIP_DEPRECATED
Definition qgis_sip.h:113
#define SIP_SKIP
Definition qgis_sip.h:133
#define SIP_IF_FEATURE(feature)
Definition qgis_sip.h:188
#define SIP_INOUT
Definition qgis_sip.h:78
#define SIP_END
Definition qgis_sip.h:215
QHash< QString, QgsAuthMethodConfig > QgsAuthMethodConfigsMap
QHash< QString, QgsAuthMethod * > QgsAuthMethodsMap