File indexing completed on 2024-04-28 04:43:41

0001 /*
0002  * qca_keystore.h - Qt Cryptographic Architecture
0003  * Copyright (C) 2003-2007  Justin Karneges <justin@affinix.com>
0004  * Copyright (C) 2004,2005  Brad Hards <bradh@frogmouth.net>
0005  *
0006  * This library is free software; you can redistribute it and/or
0007  * modify it under the terms of the GNU Lesser General Public
0008  * License as published by the Free Software Foundation; either
0009  * version 2.1 of the License, or (at your option) any later version.
0010  *
0011  * This library is distributed in the hope that it will be useful,
0012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
0013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0014  * Lesser General Public License for more details.
0015  *
0016  * You should have received a copy of the GNU Lesser General Public
0017  * License along with this library; if not, write to the Free Software
0018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
0019  * 02110-1301  USA
0020  *
0021  */
0022 
0023 /**
0024    \file qca_keystore.h
0025 
0026    Header file for classes that provide and manage keys
0027 
0028    \note You should not use this header directly from an
0029    application. You should just use <tt> \#include \<QtCrypto>
0030    </tt> instead.
0031 */
0032 
0033 #ifndef QCA_KEYSTORE_H
0034 #define QCA_KEYSTORE_H
0035 
0036 #include "qca_cert.h"
0037 #include "qca_core.h"
0038 
0039 namespace QCA {
0040 
0041 class KeyStoreTracker;
0042 class KeyStoreManagerPrivate;
0043 class KeyStorePrivate;
0044 
0045 /**
0046    \class KeyStoreEntry qca_keystore.h QtCrypto
0047 
0048    Single entry in a KeyStore
0049 
0050    This is a container for any kind of object in a KeyStore
0051    (such as PGP keys, or X.509 certificates / private keys).
0052 
0053    KeyStoreEntry objects are obtained through KeyStore or loaded from a
0054    serialized string format.  The latter method requires a KeyStoreEntry
0055    obtained through KeyStore to be serialized for future loading.  For
0056    example:
0057 
0058    \code
0059 QString str = someKeyStoreEntry.toString();
0060 [ app saves str to disk ]
0061 [ app quits ]
0062 ...
0063 [ app launches ]
0064 [ app reads str from disk ]
0065 KeyStoreEntry entry(str);
0066 printf("Entry name: [%s]\n", qPrintable(entry.name()));
0067    \endcode
0068 
0069    KeyStoreEntry objects may or may not be available.  An entry is
0070    unavailable if it has a private content that is not present.  The
0071    private content might exist on external hardware.  To determine if an
0072    entry is available, call isAvailable().  To ensure an entry is available
0073    before performing a private key operation, call ensureAvailable.  For
0074    example:
0075 
0076    \code
0077 if(entry.ensureAvailable())
0078 {
0079    entry.keyBundle().privateKey().signMessage(...);
0080    ...
0081 }
0082    \endcode
0083 
0084    ensureAvailable() blocks and may cause hardware access, but
0085    if it completes successfully then you may use the entry's private
0086    content.  It also means, in the case of a Smart Card token, that
0087    it is probably inserted.
0088 
0089    To watch this entry asynchronously, you would do:
0090 
0091    \code
0092 KeyStoreEntryWatcher *watcher = new KeyStoreEntryWatcher(entry);
0093 connect(watcher, &KeyStoreEntryWatcher::available, this, &YourClass::entry_available);
0094 ...
0095 void entry_available()
0096 {
0097    // entry now available
0098    watcher->entry().keyBundle().privateKey().signMessage(...);
0099 }
0100    \endcode
0101 
0102    Unlike private content, public content is always usable even if the
0103    entry is not available.  Serialized entry data contains all of the
0104    metadata necessary to reconstruct the public content.
0105 
0106    Now, even though an entry may be available, it does not
0107    mean you have access to use it for operations.  For
0108    example, even though a KeyBundle entry offered by a Smart Card
0109    may be available, as soon as you try to use the PrivateKey object
0110    for a signing operation, a PIN might be asked for.  You can call
0111    ensureAccess() if you want to synchronously provide the PIN
0112    early on:
0113 
0114    \code
0115 if(entry.ensureAccess())
0116 {
0117    // do private key stuff
0118    ...
0119 }
0120    \endcode
0121 
0122    Note that you don't have to call ensureAvailable() before
0123    ensureAccess().  Calling the latter is enough to imply
0124    both.
0125 
0126    After an application is configured to use a particular key,
0127    it is expected that its usual running procedure will be:
0128 
0129    1) Construct KeyStoreEntry from the serialized data.
0130    2) If the content object is not available, wait for it
0131    (with either ensureAvailable() or KeyStoreEntryWatcher).
0132    3) Pass the content object(s) to a high level operation like TLS.
0133 
0134    In this case, any PIN prompting and private key operations
0135    would be caused/handled from the TLS object.  Omit step 2 and
0136    the private key operations might cause token prompting.
0137 
0138    \ingroup UserAPI
0139 */
0140 class QCA_EXPORT KeyStoreEntry : public Algorithm
0141 {
0142 public:
0143     /**
0144        The type of entry in the KeyStore
0145     */
0146     enum Type
0147     {
0148         TypeKeyBundle,
0149         TypeCertificate,
0150         TypeCRL,
0151         TypePGPSecretKey,
0152         TypePGPPublicKey
0153     };
0154 
0155     /**
0156        Create an empty KeyStoreEntry
0157     */
0158     KeyStoreEntry();
0159 
0160     /**
0161        Create a passive KeyStoreEntry based on a serialized
0162        string
0163 
0164        \param serialized the string containing the keystore entry information
0165 
0166        \sa fromString
0167     */
0168     KeyStoreEntry(const QString &serialized);
0169 
0170     /**
0171        Standard copy constructor
0172 
0173        \param from the source entry
0174     */
0175     KeyStoreEntry(const KeyStoreEntry &from);
0176 
0177     ~KeyStoreEntry() override;
0178 
0179     /**
0180        Standard assignment operator
0181 
0182        \param from the source entry
0183     */
0184     KeyStoreEntry &operator=(const KeyStoreEntry &from);
0185 
0186     /**
0187        Test if this key is empty (null)
0188     */
0189     bool isNull() const;
0190 
0191     /**
0192        Test if the key is available for use.
0193 
0194        A key is considered available if the key's private
0195        content is present.
0196 
0197        \sa ensureAvailable
0198        \sa isAccessible
0199     */
0200     bool isAvailable() const;
0201 
0202     /**
0203        Test if the key is currently accessible.
0204 
0205        This means that the private key part can be used
0206        at this time. For a smartcard, this means that all
0207        required operations (e.g. login / PIN entry) are
0208        completed.
0209 
0210        If isAccessible() is true, then the key
0211        is necessarily available (i.e. isAvailable() is
0212        also true).
0213 
0214        \sa ensureAccessible
0215        \sa isAvailable
0216     */
0217     bool isAccessible() const;
0218 
0219     /**
0220        Determine the type of key stored in this object
0221     */
0222     Type type() const;
0223 
0224     /**
0225        The name associated with the key stored in this object
0226     */
0227     QString name() const;
0228 
0229     /**
0230        The ID associated with the key stored in this object.
0231     */
0232     QString id() const;
0233 
0234     /**
0235        The name of the KeyStore for this key object
0236     */
0237     QString storeName() const;
0238 
0239     /**
0240        The id of the KeyStore for this key object
0241 
0242        \sa KeyStore::id()
0243     */
0244     QString storeId() const;
0245 
0246     /**
0247        Serialize into a string for use as a passive entry
0248     */
0249     QString toString() const;
0250 
0251     /**
0252        Load a passive entry by using a serialized string
0253        as input
0254 
0255        \param serialized the string containing the keystore entry information
0256 
0257        \return the newly created KeyStoreEntry
0258     */
0259     static KeyStoreEntry fromString(const QString &serialized);
0260 
0261     /**
0262        If a KeyBundle is stored in this object, return that
0263        bundle.
0264     */
0265     KeyBundle keyBundle() const;
0266 
0267     /**
0268        If a Certificate is stored in this object, return that
0269        certificate.
0270     */
0271     Certificate certificate() const;
0272 
0273     /**
0274        If a CRL is stored in this object, return the value
0275        of the CRL
0276     */
0277     CRL crl() const;
0278 
0279     /**
0280        If the key stored in this object is a private
0281        PGP key, return the contents of that key.
0282     */
0283     PGPKey pgpSecretKey() const;
0284 
0285     /**
0286        If the key stored in this object is either an
0287        public or private PGP key, extract the public key
0288        part of that PGP key.
0289     */
0290     PGPKey pgpPublicKey() const;
0291 
0292     /**
0293        Returns true if the entry is available, otherwise false.
0294 
0295        Available means that any private content for this entry is
0296        present and ready for use.  In the case of a smart card, this
0297        will ensure the card is inserted, and may invoke a token
0298        prompt.
0299 
0300        Calling this function on an already available entry may cause
0301        the entry to be refreshed.
0302 
0303        \sa isAvailable
0304        \sa ensureAccess
0305 
0306        \note This function is blocking.
0307        \note This synchronous operation may require event handling, and so
0308        it must not be called from the same thread as an EventHandler.
0309     */
0310     bool ensureAvailable();
0311 
0312     /**
0313        Like ensureAvailable, but will also ensure
0314        that the PIN is provided if needed.
0315 
0316        \sa isAccessible
0317        \sa ensureAvailable
0318 
0319        \note This synchronous operation may require event handling, and so
0320        it must not be called from the same thread as an EventHandler.
0321     */
0322     bool ensureAccess();
0323 
0324 private:
0325     class Private;
0326     Private *d;
0327 
0328     friend class KeyStoreTracker;
0329 };
0330 
0331 /**
0332    \class KeyStoreEntryWatcher qca_keystore.h QtCrypto
0333 
0334    Class to monitor the availability of a KeyStoreEntry
0335 
0336    Some KeyStore types have the concept of an entry that can be
0337    available only part of the time (for example, a smart card that
0338    can be removed). This class allows you to identify when a
0339    KeyStoreEntry becomes available / unavailable.
0340 
0341    \note You can also monitor availability of a whole KeyStore,
0342    using KeyStoreManager::keyStoreAvailable() signal, and
0343    the KeyStore::unavailable() signal.
0344 
0345    \sa KeyStore for more discussion on availability of
0346    keys and related objects.
0347 
0348    \ingroup UserAPI
0349 */
0350 class QCA_EXPORT KeyStoreEntryWatcher : public QObject
0351 {
0352     Q_OBJECT
0353 public:
0354     /**
0355        Standard constructor.
0356 
0357        This creates an object that monitors the specified KeyStore entry,
0358        emitting available() and unavailable() as the entry becomes available
0359        and unavailable respectively.
0360 
0361        \param e the KeyStoreEntry to monitor
0362        \param parent the parent object for this object
0363     */
0364     explicit KeyStoreEntryWatcher(const KeyStoreEntry &e, QObject *parent = nullptr);
0365 
0366     ~KeyStoreEntryWatcher() override;
0367 
0368     /**
0369        The KeyStoreEntry that is being monitored
0370     */
0371     KeyStoreEntry entry() const;
0372 
0373 Q_SIGNALS:
0374     /**
0375        This signal is emitted when the entry that is being monitored
0376        becomes available.
0377     */
0378     void available();
0379 
0380     /**
0381        This signal is emitted when the entry that is being monitored
0382        becomes unavailble.
0383     */
0384     void unavailable();
0385 
0386 private:
0387     Q_DISABLE_COPY(KeyStoreEntryWatcher)
0388 
0389     class Private;
0390     friend class Private;
0391     Private *d;
0392 };
0393 
0394 /**
0395    \class KeyStore qca_keystore.h QtCrypto
0396 
0397    General purpose key storage object
0398 
0399    Examples of use of this are:
0400     -  systemstore:          System TrustedCertificates
0401     -  accepted self-signed: Application TrustedCertificates
0402     -  apple keychain:       User Identities
0403     -  smartcard:            SmartCard Identities
0404     -  gnupg:                PGPKeyring Identities,PGPPublicKeys
0405 
0406     \note
0407     - there can be multiple KeyStore objects referring to the same id
0408     - when a KeyStore is constructed, it refers to a given id (deviceId)
0409     and internal contextId.  if the context goes away, the KeyStore
0410     becomes invalid (isValid() == false), and unavailable() is emitted.
0411     even if the device later reappears, the KeyStore remains invalid.
0412     a new KeyStore will have to be created to use the device again.
0413 
0414    \ingroup UserAPI
0415 */
0416 class QCA_EXPORT KeyStore : public QObject, public Algorithm
0417 {
0418     Q_OBJECT
0419 public:
0420     /**
0421        The type of keystore
0422     */
0423     enum Type
0424     {
0425         System,      ///< objects such as root certificates
0426         User,        ///< objects such as Apple Keychain, KDE Wallet
0427         Application, ///< for caching accepted self-signed certificates
0428         SmartCard,   ///< for smartcards
0429         PGPKeyring   ///< for a PGP keyring
0430     };
0431 
0432     /**
0433        Obtain a specific KeyStore
0434 
0435        \param id the identification for the key store
0436        \param keyStoreManager the parent manager for this keystore
0437     */
0438     KeyStore(const QString &id, KeyStoreManager *keyStoreManager);
0439 
0440     ~KeyStore() override;
0441 
0442     /**
0443        Check if this KeyStore is valid
0444 
0445        \return true if the KeyStore is valid
0446     */
0447     bool isValid() const;
0448 
0449     /**
0450        The KeyStore Type
0451     */
0452     Type type() const;
0453 
0454     /**
0455        The name associated with the KeyStore
0456     */
0457     QString name() const;
0458 
0459     /**
0460        The ID associated with the KeyStore
0461     */
0462     QString id() const;
0463 
0464     /**
0465        Test if the KeyStore is writeable or not
0466 
0467        \return true if the KeyStore is read-only
0468     */
0469     bool isReadOnly() const;
0470 
0471     /**
0472        Turns on asynchronous mode for this KeyStore instance.
0473 
0474        Normally, entryList() and writeEntry() are blocking
0475        calls.  However, if startAsynchronousMode() is called,
0476        then these functions will return immediately.  entryList()
0477        will return with the latest known entries, or an empty
0478        list if none are known yet (in this mode, updated() will
0479        be emitted once the initial entries are known, even if the
0480        store has not actually been altered).  writeEntry() will
0481        always return an empty string, and the entryWritten()
0482        signal indicates the result of a write.
0483     */
0484     void startAsynchronousMode();
0485 
0486     /**
0487        A list of the KeyStoreEntry objects in this store
0488 
0489        \note This synchronous operation may require event handling, and so
0490        it must not be called from the same thread as an EventHandler
0491        (this is not a concern if asynchronous mode is enabled).
0492 
0493        \sa startAsynchronousMode
0494     */
0495     QList<KeyStoreEntry> entryList() const;
0496 
0497     /**
0498        test if the KeyStore holds trusted certificates (and CRLs)
0499     */
0500     bool holdsTrustedCertificates() const;
0501 
0502     /**
0503        test if the KeyStore holds identities (eg KeyBundle or PGPSecretKey)
0504     */
0505     bool holdsIdentities() const;
0506 
0507     /**
0508        test if the KeyStore holds PGPPublicKey objects
0509     */
0510     bool holdsPGPPublicKeys() const;
0511 
0512     /**
0513        Add a entry to the KeyStore
0514 
0515        Returns the entryId of the written entry or an empty
0516        string on failure.
0517 
0518        \param kb the KeyBundle to add to the KeyStore
0519 
0520        \note This synchronous operation may require event handling, and so
0521        it must not be called from the same thread as an EventHandler
0522        (this is not a concern if asynchronous mode is enabled).
0523 
0524        \sa startAsynchronousMode
0525     */
0526     QString writeEntry(const KeyBundle &kb);
0527 
0528     /**
0529        \overload
0530 
0531        \param cert the Certificate to add to the KeyStore
0532     */
0533     QString writeEntry(const Certificate &cert);
0534 
0535     /**
0536        \overload
0537 
0538        \param crl the CRL to add to the KeyStore
0539     */
0540     QString writeEntry(const CRL &crl);
0541 
0542     /**
0543        \overload
0544 
0545        \param key the PGPKey to add to the KeyStore
0546 
0547        \return a ref to the key in the keyring
0548     */
0549     QString writeEntry(const PGPKey &key);
0550 
0551     /**
0552        Delete the a specified KeyStoreEntry from this KeyStore
0553 
0554        \param id the ID for the entry to be deleted
0555 
0556        \note This synchronous operation may require event handling, and so
0557        it must not be called from the same thread as an EventHandler
0558        (this is not a concern if asynchronous mode is enabled).
0559 
0560        \sa startAsynchronousMode
0561     */
0562     bool removeEntry(const QString &id);
0563 
0564 Q_SIGNALS:
0565     /**
0566        Emitted when the KeyStore is changed
0567 
0568        This occurs if entries are added, removed, or changed in this
0569        KeyStore, including changes in entry availability.
0570     */
0571     void updated();
0572 
0573     /**
0574        Emitted when the KeyStore becomes unavailable
0575     */
0576     void unavailable();
0577 
0578     /**
0579        Emitted when an entry has been written, in asynchronous
0580        mode.
0581 
0582        \param entryId is the newly written entry id on success,
0583        or an empty string if the write failed.
0584     */
0585     void entryWritten(const QString &entryId);
0586 
0587     /**
0588        Emitted when an entry has been removed, in asynchronous
0589        mode.
0590 
0591        \param success indicates if the removal succeeded (true) or not (false).
0592     */
0593     void entryRemoved(bool success);
0594 
0595 private:
0596     Q_DISABLE_COPY(KeyStore)
0597 
0598     friend class KeyStorePrivate;
0599     KeyStorePrivate *d;
0600 
0601     friend class KeyStoreManagerPrivate;
0602 };
0603 
0604 /**
0605    \class KeyStoreInfo qca_keystore.h QtCrypto
0606 
0607    Key store information, outside of a KeyStore object
0608 
0609    This class is used in conjunction with the Event class,
0610    and related classes such as PasswordAsker and TokenAsker,
0611    to describe the key store source of the Event.
0612 
0613    Each KeyStoreInfo represents a single KeyStore, and describes
0614    the type of store (e.g. smartcard or PGP keyring - see
0615    KeyStore::Type), and a couple of names. The id() of a KeyStore
0616    is used to reference it, and is typically of the form
0617    "qca-mystorename". The name() of a KeyStore is used to describe
0618    it (i.e. this is the "pretty" name to show the user), and is
0619    typically of the form "My Store Name".
0620 
0621    \ingroup UserAPI
0622 */
0623 class QCA_EXPORT KeyStoreInfo
0624 {
0625 public:
0626     /**
0627        Constructor.
0628 
0629        \note This form of constructor for KeyStoreInfo
0630        produces an object that does not describe any
0631        KeyStore, and isNull() will return true.
0632     */
0633     KeyStoreInfo();
0634 
0635     /**
0636        Standard constructor.
0637 
0638        This builds a KeyStoreInfo object that descibes a
0639        KeyStore.
0640 
0641        \param type the type of KeyStore
0642        \param id the identification of the KeyStore
0643        \param name the descriptive name of the KeyStore
0644     */
0645     KeyStoreInfo(KeyStore::Type type, const QString &id, const QString &name);
0646 
0647     /**
0648        Copy constructor.
0649 
0650        \param from the KeyStoreInfo to copy from
0651     */
0652     KeyStoreInfo(const KeyStoreInfo &from);
0653 
0654     ~KeyStoreInfo();
0655 
0656     /**
0657        Assignment operator.
0658 
0659        \param from the KeyStoreInfo to copy from
0660     */
0661     KeyStoreInfo &operator=(const KeyStoreInfo &from);
0662 
0663     /**
0664        Test if this object is valid
0665 
0666        \return true if the object is not valid
0667     */
0668     bool isNull() const;
0669 
0670     /**
0671        The Type of KeyStore that this KeyStoreInfo object
0672        describes.
0673     */
0674     KeyStore::Type type() const;
0675 
0676     /**
0677        The unique identification of the KeyStore that
0678        this KeyStoreInfo object describes.
0679     */
0680     QString id() const;
0681 
0682     /**
0683        The descriptive name of the KeyStore that this
0684        KeyStoreInfo object describes.
0685     */
0686     QString name() const;
0687 
0688 private:
0689     class Private;
0690     QSharedDataPointer<Private> d;
0691 };
0692 
0693 /**
0694    \class KeyStoreManager qca_keystore.h QtCrypto
0695 
0696    Access keystores, and monitor keystores for changes.
0697 
0698    Before you can access a KeyStore, you must create a
0699    KeyStoreManager. You then need to start()
0700    the KeyStoreManager, and either wait for the busyFinished()
0701    signal, or block using waitForBusyFinished().
0702 
0703    If you know the KeyStoreEntry that you need, you can
0704    use KeyStore passively, as described in the KeyStoreEntry
0705    documentation.
0706 
0707    \ingroup UserAPI
0708 */
0709 class QCA_EXPORT KeyStoreManager : public QObject
0710 {
0711     Q_OBJECT
0712 public:
0713     /**
0714    Create a new KeyStoreManager
0715 
0716    \param parent the parent for this object
0717 */
0718     KeyStoreManager(QObject *parent = nullptr);
0719     ~KeyStoreManager() override;
0720 
0721     /**
0722        Initialize all key store providers
0723     */
0724     static void start();
0725 
0726     /**
0727        Initialize a specific key store provider
0728 
0729        \param provider the name of the provider to start
0730     */
0731     static void start(const QString &provider);
0732 
0733     /**
0734        Indicates if the manager is busy looking for key stores
0735     */
0736     bool isBusy() const;
0737 
0738     /**
0739        Blocks until the manager is done looking for key stores
0740     */
0741     void waitForBusyFinished();
0742 
0743     /**
0744        A list of all the key stores
0745     */
0746     QStringList keyStores() const;
0747 
0748     /**
0749        The diagnostic result of key store operations, such as
0750        warnings and errors
0751     */
0752     static QString diagnosticText();
0753 
0754     /**
0755        Clears the diagnostic result log
0756     */
0757     static void clearDiagnosticText();
0758 
0759     /**
0760        If you are not using the eventloop, call this to update
0761        the object state to the present
0762     */
0763     void sync();
0764 
0765 Q_SIGNALS:
0766     /**
0767        emitted when the manager has started looking for key stores
0768     */
0769     void busyStarted();
0770 
0771     /**
0772        emitted when the manager has finished looking for key stores
0773     */
0774     void busyFinished();
0775 
0776     /**
0777        emitted when a new key store becomes available
0778 
0779        \param id the name of the key store that has become available
0780     */
0781     void keyStoreAvailable(const QString &id);
0782 
0783 private:
0784     Q_DISABLE_COPY(KeyStoreManager)
0785 
0786     friend class KeyStoreManagerPrivate;
0787     KeyStoreManagerPrivate *d;
0788 
0789     friend class Global;
0790     friend class KeyStorePrivate;
0791 
0792     static void scan();
0793     static void shutdown();
0794 };
0795 
0796 }
0797 
0798 #endif