QGIS API Documentation 3.99.0-Master (26c88405ac0)
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#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
43#include <qt6keychain/keychain.h>
44#else
45#include <qt5keychain/keychain.h>
46#endif
47
48#ifndef SIP_RUN
49namespace QCA
50{
51 class Initializer;
52}
53#endif
54class QgsAuthMethod;
56class QgsAuthProvider;
59class QTimer;
63
72class CORE_EXPORT QgsAuthManager : public QObject
73{
74 Q_OBJECT
75
76 public:
77
80
83 {
84 INFO = 0,
87 };
88 Q_ENUM( MessageLevel )
89
90
99 Q_DECL_DEPRECATED bool init( const QString &pluginPath = QString(), const QString &authDatabasePath = QString() ) SIP_DEPRECATED;
100
111 void setup( const QString &pluginPath = QString(), const QString &authDatabasePath = QString() );
112
120 bool ensureInitialized() const;
121
122 ~QgsAuthManager() override;
123
128 QgsAuthConfigurationStorageRegistry *authConfigurationStorageRegistry() const;
129
135 Q_DECL_DEPRECATED QSqlDatabase authDatabaseConnection() const SIP_DEPRECATED;
136
141 Q_DECL_DEPRECATED const QString authDatabaseConfigTable() const SIP_DEPRECATED { return AUTH_CONFIG_TABLE; }
142
148 const QString methodConfigTableName() const;
149
154 Q_DECL_DEPRECATED const QString authDatabaseServersTable() const SIP_DEPRECATED { return AUTH_SERVERS_TABLE; }
155
156
158 bool isDisabled() const;
159
161 const QString disabledMessage() const;
162
168 Q_DECL_DEPRECATED const QString authenticationDatabasePath() const;
169
173 static bool isFilesystemBasedDatabase( const QString &uri );
174
180 QgsAuthConfigurationStorageDb *defaultDbStorage() const SIP_SKIP;
181
186 const QString authenticationDatabaseUri() const;
187
192 const QString authenticationDatabaseUriStripped() const;
193
201 bool createAndStoreRandomMasterPasswordInKeyChain() SIP_SKIP;
202
208 bool setMasterPassword( bool verify = false );
209
216 bool setMasterPassword( const QString &password, bool verify = false );
217
223 bool verifyMasterPassword( const QString &compare = QString() );
224
226 bool masterPasswordIsSet() const;
227
229 bool masterPasswordHashInDatabase() const;
230
235 void clearMasterPassword() { mMasterPass = QString(); }
236
241 bool masterPasswordSame( const QString &password ) const;
242
252 bool resetMasterPassword( const QString &newpass, const QString &oldpass, bool keepbackup, QString *backuppath SIP_INOUT = nullptr );
253
267 bool resetMasterPasswordUsingStoredPasswordHelper( const QString &newPassword, bool keepBackup, QString *backupPath = nullptr ) SIP_SKIP;
268
273 bool scheduledAuthDatabaseErase() SIP_SKIP { return mScheduledDbErase; }
274
287 void setScheduledAuthDatabaseErase( bool scheduleErase ) SIP_SKIP;
288
297 void setScheduledAuthDatabaseEraseRequestEmitted( bool emitted ) { mScheduledDbEraseRequestEmitted = emitted; }
298
300 QString authManTag() const { return AUTH_MAN_TAG; }
301
303 bool registerCoreAuthMethods();
304
306 QgsAuthMethodConfigsMap availableAuthMethodConfigs( const QString &dataprovider = QString() );
307
309 void updateConfigAuthMethods();
310
315 QgsAuthMethod *configAuthMethod( const QString &authcfg );
316
321 QString configAuthMethodKey( const QString &authcfg ) const;
322
326 QStringList authMethodsKeys( const QString &dataprovider = QString() );
327
332 QgsAuthMethod *authMethod( const QString &authMethodKey );
333
339 const QgsAuthMethodMetadata *authMethodMetadata( const QString &authMethodKey ) SIP_SKIP;
340
346 QgsAuthMethodsMap authMethodsMap( const QString &dataprovider = QString() ) SIP_SKIP;
347
348#ifdef HAVE_GUI
349 SIP_IF_FEATURE( HAVE_GUI )
350
351
356 QWidget *authMethodEditWidget( const QString &authMethodKey, QWidget *parent );
357 SIP_END
358#endif
359
364 QgsAuthMethod::Expansions supportedAuthMethodExpansions( const QString &authcfg );
365
367 const QString uniqueConfigId() const;
368
373 bool configIdUnique( const QString &id ) const;
374
379 static bool hasConfigId( const QString &txt );
380
382 QString configIdRegex() const { return AUTH_CFG_REGEX;}
383
385 QStringList configIds() const;
386
393 bool storeAuthenticationConfig( QgsAuthMethodConfig &mconfig SIP_INOUT, bool overwrite = false );
394
400 bool updateAuthenticationConfig( const QgsAuthMethodConfig &config );
401
409 bool loadAuthenticationConfig( const QString &authcfg, QgsAuthMethodConfig &mconfig SIP_INOUT, bool full = false );
410
416 bool removeAuthenticationConfig( const QString &authcfg );
417
425 bool exportAuthenticationConfigsToXml( const QString &filename, const QStringList &authcfgs, const QString &password = QString() );
426
434 bool importAuthenticationConfigsFromXml( const QString &filename, const QString &password = QString(), bool overwrite = false );
435
440 bool removeAllAuthenticationConfigs();
441
446 bool backupAuthenticationDatabase( QString *backuppath SIP_INOUT = nullptr );
447
454 bool eraseAuthenticationDatabase( bool backup, QString *backuppath SIP_INOUT = nullptr );
455
456
458
466 bool updateNetworkRequest( QNetworkRequest &request SIP_INOUT, const QString &authcfg,
467 const QString &dataprovider = QString() );
468
476 bool updateNetworkReply( QNetworkReply *reply, const QString &authcfg,
477 const QString &dataprovider = QString() );
478
486 bool updateDataSourceUriItems( QStringList &connectionItems SIP_INOUT, const QString &authcfg,
487 const QString &dataprovider = QString() );
488
496 bool updateNetworkProxy( QNetworkProxy &proxy SIP_INOUT, const QString &authcfg,
497 const QString &dataprovider = QString() );
498
500
508 bool storeAuthSetting( const QString &key, const QVariant &value, bool encrypt = false );
509
522 QVariant authSetting( const QString &key, const QVariant &defaultValue = QVariant(), bool decrypt = false );
523
525 bool existsAuthSetting( const QString &key );
526
528 bool removeAuthSetting( const QString &key );
529
530#ifndef QT_NO_SSL
532
534 bool initSslCaches();
535
537 bool storeCertIdentity( const QSslCertificate &cert, const QSslKey &key );
538
544 const QSslCertificate certIdentity( const QString &id );
545
552 const QPair<QSslCertificate, QSslKey> certIdentityBundle( const QString &id ) SIP_SKIP;
553
559 const QStringList certIdentityBundleToPem( const QString &id );
560
565 const QList<QSslCertificate> certIdentities();
566
568
573 QStringList certIdentityIds() const;
574
576 bool existsCertIdentity( const QString &id );
577
579 bool removeCertIdentity( const QString &id );
580
581
583 bool storeSslCertCustomConfig( const QgsAuthConfigSslServer &config );
584
591 const QgsAuthConfigSslServer sslCertCustomConfig( const QString &id, const QString &hostport );
592
598 const QgsAuthConfigSslServer sslCertCustomConfigByHost( const QString &hostport );
599
604 const QList<QgsAuthConfigSslServer> sslCertCustomConfigs();
605
607 bool existsSslCertCustomConfig( const QString &id, const QString &hostport );
608
610 bool removeSslCertCustomConfig( const QString &id, const QString &hostport );
611
617 QHash<QString, QSet<QSslError::SslError> > ignoredSslErrorCache() SIP_SKIP { return mIgnoredSslErrorsCache; }
618
620 void dumpIgnoredSslErrorsCache_();
621
623 bool updateIgnoredSslErrorsCacheFromConfig( const QgsAuthConfigSslServer &config );
624
626 bool updateIgnoredSslErrorsCache( const QString &shahostport, const QList<QSslError> &errors );
627
629 bool rebuildIgnoredSslErrorCache();
630
631
633 bool storeCertAuthorities( const QList<QSslCertificate> &certs );
634
636 bool storeCertAuthority( const QSslCertificate &cert );
637
639
645 const QSslCertificate certAuthority( const QString &id );
646
648 bool existsCertAuthority( const QSslCertificate &cert );
649
651 bool removeCertAuthority( const QSslCertificate &cert );
652
657 static const QList<QSslCertificate> systemRootCAs();
658
663 const QList<QSslCertificate> extraFileCAs();
664
669 const QList<QSslCertificate> databaseCAs();
670
675 const QMap<QString, QSslCertificate> mappedDatabaseCAs();
676
682 const QMap<QString, QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > caCertsCache() SIP_SKIP
683 {
684 return mCaCertsCache;
685 }
686
688 bool rebuildCaCertsCache();
689
691 bool storeCertTrustPolicy( const QSslCertificate &cert, QgsAuthCertUtils::CertTrustPolicy policy );
692
698 QgsAuthCertUtils::CertTrustPolicy certTrustPolicy( const QSslCertificate &cert );
699
701 bool removeCertTrustPolicies( const QList<QSslCertificate> &certs );
702
704 bool removeCertTrustPolicy( const QSslCertificate &cert );
705
711 QgsAuthCertUtils::CertTrustPolicy certificateTrustPolicy( const QSslCertificate &cert );
712
714 bool setDefaultCertTrustPolicy( QgsAuthCertUtils::CertTrustPolicy policy );
715
717 QgsAuthCertUtils::CertTrustPolicy defaultCertTrustPolicy();
718
723 const QMap<QgsAuthCertUtils::CertTrustPolicy, QStringList > certTrustCache() { return mCertTrustCache; }
724
726 bool rebuildCertTrustCache();
727
733 const QList<QSslCertificate> trustedCaCerts( bool includeinvalid = false );
734
739 const QList<QSslCertificate> untrustedCaCerts( QList<QSslCertificate> trustedCAs = QList<QSslCertificate>() );
740
742 bool rebuildTrustedCaCertsCache();
743
748 const QList<QSslCertificate> trustedCaCertsCache() { return mTrustedCaCertsCache; }
749
754 const QByteArray trustedCaCertsPemText();
755
756#endif
757
762 const QString passwordHelperErrorMessage() SIP_SKIP { return mPasswordHelperErrorMessage; }
763
768 bool passwordHelperDelete() SIP_SKIP;
769
774 static bool passwordHelperEnabled();
775
780 void setPasswordHelperEnabled( bool enabled );
781
786 static bool passwordHelperLoggingEnabled() SIP_SKIP;
787
792 static void setPasswordHelperLoggingEnabled( bool enabled ) SIP_SKIP;
793
798 bool passwordHelperSync();
799
806 bool verifyStoredPasswordHelperPassword() SIP_SKIP;
807
808 // TODO QGIS 4.0 -- remove
809
816
825 static QString passwordHelperDisplayName( bool titleCase = false );
826
828 static const QString AUTH_MAN_TAG;
829
835 QString sqliteDatabasePath() const SIP_SKIP;
836
837 signals:
838
844
850
859 Q_DECL_DEPRECATED void messageOut( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level = QgsAuthManager::INFO ) const SIP_DEPRECATED;
860
869 void messageLog( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level = Qgis::MessageLevel::Info ) const;
870
879 Q_DECL_DEPRECATED void passwordHelperMessageOut( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, QgsAuthManager::MessageLevel level = QgsAuthManager::INFO ) SIP_DEPRECATED;
880
889 void passwordHelperMessageLog( const QString &message, const QString &tag = QgsAuthManager::AUTH_MAN_TAG, Qgis::MessageLevel level = Qgis::MessageLevel::Info );
890
895 void masterPasswordVerified( bool verified );
896
899
902
903 public slots:
906
908 void clearCachedConfig( const QString &authcfg );
909
910 private slots:
911 void writeToConsole( const QString &message, const QString &tag = QString(), Qgis::MessageLevel level = Qgis::MessageLevel::Info );
912
922 void tryToStartDbErase();
923
924 protected:
925
931
932
933#ifdef Q_OS_WIN
934 public:
935 explicit QgsAuthManager() SIP_SKIP;
936#else
937 protected:
938 explicit QgsAuthManager() SIP_SKIP;
939#endif
940
941 private:
942
946 static QString generatePassword();
947
948 bool initPrivate( const QString &pluginPath );
949
951 // Password Helper methods
952
954 QString passwordHelperName() const;
955
957 void passwordHelperLog( const QString &msg ) const;
958
960 QString passwordHelperRead( bool &ok );
961
963 bool passwordHelperWrite( const QString &password );
964
966 void passwordHelperSetErrorMessage( const QString &errorMessage ) { mPasswordHelperErrorMessage = errorMessage; }
967
969 void passwordHelperClearErrors();
970
975 void passwordHelperProcessError();
976
977 bool masterPasswordInput();
978
985 bool masterPasswordRowsInDb( int &rows ) const;
986
987 bool masterPasswordCheckAgainstDb( const QString &compare = QString() ) const;
988
989 bool masterPasswordStoreInDb() const;
990
991 bool masterPasswordClearDb();
992
993 const QString masterPasswordCiv() const;
994
995 bool verifyPasswordCanDecryptConfigs() const;
996
997 bool reencryptAllAuthenticationConfigs( const QString &prevpass, const QString &prevciv );
998
999 bool reencryptAuthenticationConfig( const QString &authcfg, const QString &prevpass, const QString &prevciv );
1000
1001 bool reencryptAllAuthenticationSettings( const QString &prevpass, const QString &prevciv );
1002
1003 bool reencryptAllAuthenticationIdentities( const QString &prevpass, const QString &prevciv );
1004
1005 bool reencryptAuthenticationIdentity( const QString &identid, const QString &prevpass, const QString &prevciv );
1006
1007#ifndef QT_NO_SSL
1008 void insertCaCertInCache( QgsAuthCertUtils::CaCertSource source, const QList<QSslCertificate> &certs );
1009#endif
1010
1011 QString authPasswordHelperKeyName() const;
1012
1016 QgsAuthConfigurationStorage *firstStorageWithCapability( Qgis::AuthConfigurationStorageCapability capability ) const;
1017
1018 static QgsAuthManager *sInstance;
1019 static const QString AUTH_CONFIG_TABLE;
1020 static const QString AUTH_SERVERS_TABLE;
1021 static const QString AUTH_CFG_REGEX;
1022
1023 QString mPluginPath;
1024 QString mAuthDatabaseConnectionUri;
1025
1026 mutable bool mLazyInitResult = false;
1027 bool mAuthInit = false;
1028
1029 mutable std::unique_ptr<QgsAuthConfigurationStorageRegistry> mAuthConfigurationStorageRegistry;
1030
1031 std::unique_ptr<QCA::Initializer> mQcaInitializer;
1032
1033 QHash<QString, QString> mConfigAuthMethods;
1034 QHash<QString, QgsAuthMethod *> mAuthMethods;
1035
1036 QString mMasterPass;
1037 int mPassTries = 0;
1038 bool mAuthDisabled = false;
1039 QString mAuthDisabledMessage;
1040 std::unique_ptr<QTimer> mScheduledDbEraseTimer;
1041 bool mScheduledDbErase = false;
1042 int mScheduledDbEraseRequestWait = 3 ; // in seconds
1043 bool mScheduledDbEraseRequestEmitted = false;
1044 int mScheduledDbEraseRequestCount = 0;
1045
1046 std::unique_ptr<QRecursiveMutex> mMutex;
1047 std::unique_ptr<QRecursiveMutex> mMasterPasswordMutex;
1048#ifndef QT_NO_SSL
1049 // mapping of sha1 digest and cert source and cert
1050 // appending removes duplicates
1051 QMap<QString, QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate> > mCaCertsCache;
1052 // list of sha1 digests per policy
1053 QMap<QgsAuthCertUtils::CertTrustPolicy, QStringList > mCertTrustCache;
1054 // cache of certs ready to be utilized in network connections
1055 QList<QSslCertificate> mTrustedCaCertsCache;
1056 // cache of SSL errors to be ignored in network connections, per sha-hostport
1057 QHash<QString, QSet<QSslError::SslError> > mIgnoredSslErrorsCache;
1058
1059 bool mHasCustomConfigByHost = false;
1060 bool mHasCheckedIfCustomConfigByHostExists = false;
1061 QMap< QString, QgsAuthConfigSslServer > mCustomConfigByHostCache;
1062#endif
1063
1065 // Password Helper Variables
1066
1068 bool mPasswordHelperVerificationError = false;
1069
1071 QString mPasswordHelperErrorMessage;
1072
1074 QKeychain::Error mPasswordHelperErrorCode = QKeychain::NoError;
1075
1077 bool mPasswordHelperLoggingEnabled = false;
1078
1080 bool mPasswordHelperFailedInit = false;
1081
1083 static const QLatin1String AUTH_PASSWORD_HELPER_KEY_NAME_BASE;
1084
1086 static const QLatin1String AUTH_PASSWORD_HELPER_FOLDER_NAME;
1087
1088 mutable QMap<QThread *, QMetaObject::Connection> mConnectedThreads;
1089
1090 friend class QgsApplication;
1091
1092};
1093
1094#endif // QGSAUTHMANAGER_H
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:56
AuthConfigurationStorageCapability
Authentication configuration storage capabilities.
Definition qgis.h:102
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 * 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 * 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 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:114
#define SIP_SKIP
Definition qgis_sip.h:134
#define SIP_IF_FEATURE(feature)
Definition qgis_sip.h:189
#define SIP_INOUT
Definition qgis_sip.h:79
#define SIP_END
Definition qgis_sip.h:216
QHash< QString, QgsAuthMethodConfig > QgsAuthMethodConfigsMap
QHash< QString, QgsAuthMethod * > QgsAuthMethodsMap