1/*
2 * qca_keystore.h - Qt Cryptographic Architecture
3 * Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
4 * Copyright (C) 2004,2005 Brad Hards <bradh@frogmouth.net>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 * 02110-1301 USA
20 *
21 */
22
23/**
24 \file qca_keystore.h
25
26 Header file for classes that provide and manage keys
27
28 \note You should not use this header directly from an
29 application. You should just use <tt> \#include \<QtCrypto>
30 </tt> instead.
31*/
32
33#ifndef QCA_KEYSTORE_H
34#define QCA_KEYSTORE_H
35
36#include "qca_cert.h"
37#include "qca_core.h"
38
39namespace QCA {
40
41class KeyStoreTracker;
42class KeyStoreManagerPrivate;
43class KeyStorePrivate;
44
45/**
46 \class KeyStoreEntry qca_keystore.h QtCrypto
47
48 Single entry in a KeyStore
49
50 This is a container for any kind of object in a KeyStore
51 (such as PGP keys, or X.509 certificates / private keys).
52
53 KeyStoreEntry objects are obtained through KeyStore or loaded from a
54 serialized string format. The latter method requires a KeyStoreEntry
55 obtained through KeyStore to be serialized for future loading. For
56 example:
57
58 \code
59QString str = someKeyStoreEntry.toString();
60[ app saves str to disk ]
61[ app quits ]
62...
63[ app launches ]
64[ app reads str from disk ]
65KeyStoreEntry entry(str);
66printf("Entry name: [%s]\n", qPrintable(entry.name()));
67 \endcode
68
69 KeyStoreEntry objects may or may not be available. An entry is
70 unavailable if it has a private content that is not present. The
71 private content might exist on external hardware. To determine if an
72 entry is available, call isAvailable(). To ensure an entry is available
73 before performing a private key operation, call ensureAvailable. For
74 example:
75
76 \code
77if(entry.ensureAvailable())
78{
79 entry.keyBundle().privateKey().signMessage(...);
80 ...
81}
82 \endcode
83
84 ensureAvailable() blocks and may cause hardware access, but
85 if it completes successfully then you may use the entry's private
86 content. It also means, in the case of a Smart Card token, that
87 it is probably inserted.
88
89 To watch this entry asynchronously, you would do:
90
91 \code
92KeyStoreEntryWatcher *watcher = new KeyStoreEntryWatcher(entry);
93connect(watcher, &KeyStoreEntryWatcher::available, this, &YourClass::entry_available);
94...
95void entry_available()
96{
97 // entry now available
98 watcher->entry().keyBundle().privateKey().signMessage(...);
99}
100 \endcode
101
102 Unlike private content, public content is always usable even if the
103 entry is not available. Serialized entry data contains all of the
104 metadata necessary to reconstruct the public content.
105
106 Now, even though an entry may be available, it does not
107 mean you have access to use it for operations. For
108 example, even though a KeyBundle entry offered by a Smart Card
109 may be available, as soon as you try to use the PrivateKey object
110 for a signing operation, a PIN might be asked for. You can call
111 ensureAccess() if you want to synchronously provide the PIN
112 early on:
113
114 \code
115if(entry.ensureAccess())
116{
117 // do private key stuff
118 ...
119}
120 \endcode
121
122 Note that you don't have to call ensureAvailable() before
123 ensureAccess(). Calling the latter is enough to imply
124 both.
125
126 After an application is configured to use a particular key,
127 it is expected that its usual running procedure will be:
128
129 1) Construct KeyStoreEntry from the serialized data.
130 2) If the content object is not available, wait for it
131 (with either ensureAvailable() or KeyStoreEntryWatcher).
132 3) Pass the content object(s) to a high level operation like TLS.
133
134 In this case, any PIN prompting and private key operations
135 would be caused/handled from the TLS object. Omit step 2 and
136 the private key operations might cause token prompting.
137
138 \ingroup UserAPI
139*/
140class QCA_EXPORT KeyStoreEntry : public Algorithm
141{
142public:
143 /**
144 The type of entry in the KeyStore
145 */
146 enum Type
147 {
148 TypeKeyBundle,
149 TypeCertificate,
150 TypeCRL,
151 TypePGPSecretKey,
152 TypePGPPublicKey
153 };
154
155 /**
156 Create an empty KeyStoreEntry
157 */
158 KeyStoreEntry();
159
160 /**
161 Create a passive KeyStoreEntry based on a serialized
162 string
163
164 \param serialized the string containing the keystore entry information
165
166 \sa fromString
167 */
168 KeyStoreEntry(const QString &serialized);
169
170 /**
171 Standard copy constructor
172
173 \param from the source entry
174 */
175 KeyStoreEntry(const KeyStoreEntry &from);
176
177 ~KeyStoreEntry() override;
178
179 /**
180 Standard assignment operator
181
182 \param from the source entry
183 */
184 KeyStoreEntry &operator=(const KeyStoreEntry &from);
185
186 /**
187 Test if this key is empty (null)
188 */
189 bool isNull() const;
190
191 /**
192 Test if the key is available for use.
193
194 A key is considered available if the key's private
195 content is present.
196
197 \sa ensureAvailable
198 \sa isAccessible
199 */
200 bool isAvailable() const;
201
202 /**
203 Test if the key is currently accessible.
204
205 This means that the private key part can be used
206 at this time. For a smartcard, this means that all
207 required operations (e.g. login / PIN entry) are
208 completed.
209
210 If isAccessible() is true, then the key
211 is necessarily available (i.e. isAvailable() is
212 also true).
213
214 \sa ensureAccessible
215 \sa isAvailable
216 */
217 bool isAccessible() const;
218
219 /**
220 Determine the type of key stored in this object
221 */
222 Type type() const;
223
224 /**
225 The name associated with the key stored in this object
226 */
227 QString name() const;
228
229 /**
230 The ID associated with the key stored in this object.
231 */
232 QString id() const;
233
234 /**
235 The name of the KeyStore for this key object
236 */
237 QString storeName() const;
238
239 /**
240 The id of the KeyStore for this key object
241
242 \sa KeyStore::id()
243 */
244 QString storeId() const;
245
246 /**
247 Serialize into a string for use as a passive entry
248 */
249 QString toString() const;
250
251 /**
252 Load a passive entry by using a serialized string
253 as input
254
255 \param serialized the string containing the keystore entry information
256
257 \return the newly created KeyStoreEntry
258 */
259 static KeyStoreEntry fromString(const QString &serialized);
260
261 /**
262 If a KeyBundle is stored in this object, return that
263 bundle.
264 */
265 KeyBundle keyBundle() const;
266
267 /**
268 If a Certificate is stored in this object, return that
269 certificate.
270 */
271 Certificate certificate() const;
272
273 /**
274 If a CRL is stored in this object, return the value
275 of the CRL
276 */
277 CRL crl() const;
278
279 /**
280 If the key stored in this object is a private
281 PGP key, return the contents of that key.
282 */
283 PGPKey pgpSecretKey() const;
284
285 /**
286 If the key stored in this object is either an
287 public or private PGP key, extract the public key
288 part of that PGP key.
289 */
290 PGPKey pgpPublicKey() const;
291
292 /**
293 Returns true if the entry is available, otherwise false.
294
295 Available means that any private content for this entry is
296 present and ready for use. In the case of a smart card, this
297 will ensure the card is inserted, and may invoke a token
298 prompt.
299
300 Calling this function on an already available entry may cause
301 the entry to be refreshed.
302
303 \sa isAvailable
304 \sa ensureAccess
305
306 \note This function is blocking.
307 \note This synchronous operation may require event handling, and so
308 it must not be called from the same thread as an EventHandler.
309 */
310 bool ensureAvailable();
311
312 /**
313 Like ensureAvailable, but will also ensure
314 that the PIN is provided if needed.
315
316 \sa isAccessible
317 \sa ensureAvailable
318
319 \note This synchronous operation may require event handling, and so
320 it must not be called from the same thread as an EventHandler.
321 */
322 bool ensureAccess();
323
324private:
325 class Private;
326 Private *d;
327
328 friend class KeyStoreTracker;
329};
330
331/**
332 \class KeyStoreEntryWatcher qca_keystore.h QtCrypto
333
334 Class to monitor the availability of a KeyStoreEntry
335
336 Some KeyStore types have the concept of an entry that can be
337 available only part of the time (for example, a smart card that
338 can be removed). This class allows you to identify when a
339 KeyStoreEntry becomes available / unavailable.
340
341 \note You can also monitor availability of a whole KeyStore,
342 using KeyStoreManager::keyStoreAvailable() signal, and
343 the KeyStore::unavailable() signal.
344
345 \sa KeyStore for more discussion on availability of
346 keys and related objects.
347
348 \ingroup UserAPI
349*/
350class QCA_EXPORT KeyStoreEntryWatcher : public QObject
351{
352 Q_OBJECT
353public:
354 /**
355 Standard constructor.
356
357 This creates an object that monitors the specified KeyStore entry,
358 emitting available() and unavailable() as the entry becomes available
359 and unavailable respectively.
360
361 \param e the KeyStoreEntry to monitor
362 \param parent the parent object for this object
363 */
364 explicit KeyStoreEntryWatcher(const KeyStoreEntry &e, QObject *parent = nullptr);
365
366 ~KeyStoreEntryWatcher() override;
367
368 /**
369 The KeyStoreEntry that is being monitored
370 */
371 KeyStoreEntry entry() const;
372
373Q_SIGNALS:
374 /**
375 This signal is emitted when the entry that is being monitored
376 becomes available.
377 */
378 void available();
379
380 /**
381 This signal is emitted when the entry that is being monitored
382 becomes unavailble.
383 */
384 void unavailable();
385
386private:
387 Q_DISABLE_COPY(KeyStoreEntryWatcher)
388
389 class Private;
390 friend class Private;
391 Private *d;
392};
393
394/**
395 \class KeyStore qca_keystore.h QtCrypto
396
397 General purpose key storage object
398
399 Examples of use of this are:
400 - systemstore: System TrustedCertificates
401 - accepted self-signed: Application TrustedCertificates
402 - apple keychain: User Identities
403 - smartcard: SmartCard Identities
404 - gnupg: PGPKeyring Identities,PGPPublicKeys
405
406 \note
407 - there can be multiple KeyStore objects referring to the same id
408 - when a KeyStore is constructed, it refers to a given id (deviceId)
409 and internal contextId. if the context goes away, the KeyStore
410 becomes invalid (isValid() == false), and unavailable() is emitted.
411 even if the device later reappears, the KeyStore remains invalid.
412 a new KeyStore will have to be created to use the device again.
413
414 \ingroup UserAPI
415*/
416class QCA_EXPORT KeyStore : public QObject, public Algorithm
417{
418 Q_OBJECT
419public:
420 /**
421 The type of keystore
422 */
423 enum Type
424 {
425 System, ///< objects such as root certificates
426 User, ///< objects such as Apple Keychain, KDE Wallet
427 Application, ///< for caching accepted self-signed certificates
428 SmartCard, ///< for smartcards
429 PGPKeyring ///< for a PGP keyring
430 };
431
432 /**
433 Obtain a specific KeyStore
434
435 \param id the identification for the key store
436 \param keyStoreManager the parent manager for this keystore
437 */
438 KeyStore(const QString &id, KeyStoreManager *keyStoreManager);
439
440 ~KeyStore() override;
441
442 /**
443 Check if this KeyStore is valid
444
445 \return true if the KeyStore is valid
446 */
447 bool isValid() const;
448
449 /**
450 The KeyStore Type
451 */
452 Type type() const;
453
454 /**
455 The name associated with the KeyStore
456 */
457 QString name() const;
458
459 /**
460 The ID associated with the KeyStore
461 */
462 QString id() const;
463
464 /**
465 Test if the KeyStore is writeable or not
466
467 \return true if the KeyStore is read-only
468 */
469 bool isReadOnly() const;
470
471 /**
472 Turns on asynchronous mode for this KeyStore instance.
473
474 Normally, entryList() and writeEntry() are blocking
475 calls. However, if startAsynchronousMode() is called,
476 then these functions will return immediately. entryList()
477 will return with the latest known entries, or an empty
478 list if none are known yet (in this mode, updated() will
479 be emitted once the initial entries are known, even if the
480 store has not actually been altered). writeEntry() will
481 always return an empty string, and the entryWritten()
482 signal indicates the result of a write.
483 */
484 void startAsynchronousMode();
485
486 /**
487 A list of the KeyStoreEntry objects in this store
488
489 \note This synchronous operation may require event handling, and so
490 it must not be called from the same thread as an EventHandler
491 (this is not a concern if asynchronous mode is enabled).
492
493 \sa startAsynchronousMode
494 */
495 QList<KeyStoreEntry> entryList() const;
496
497 /**
498 test if the KeyStore holds trusted certificates (and CRLs)
499 */
500 bool holdsTrustedCertificates() const;
501
502 /**
503 test if the KeyStore holds identities (eg KeyBundle or PGPSecretKey)
504 */
505 bool holdsIdentities() const;
506
507 /**
508 test if the KeyStore holds PGPPublicKey objects
509 */
510 bool holdsPGPPublicKeys() const;
511
512 /**
513 Add a entry to the KeyStore
514
515 Returns the entryId of the written entry or an empty
516 string on failure.
517
518 \param kb the KeyBundle to add to the KeyStore
519
520 \note This synchronous operation may require event handling, and so
521 it must not be called from the same thread as an EventHandler
522 (this is not a concern if asynchronous mode is enabled).
523
524 \sa startAsynchronousMode
525 */
526 QString writeEntry(const KeyBundle &kb);
527
528 /**
529 \overload
530
531 \param cert the Certificate to add to the KeyStore
532 */
533 QString writeEntry(const Certificate &cert);
534
535 /**
536 \overload
537
538 \param crl the CRL to add to the KeyStore
539 */
540 QString writeEntry(const CRL &crl);
541
542 /**
543 \overload
544
545 \param key the PGPKey to add to the KeyStore
546
547 \return a ref to the key in the keyring
548 */
549 QString writeEntry(const PGPKey &key);
550
551 /**
552 Delete the a specified KeyStoreEntry from this KeyStore
553
554 \param id the ID for the entry to be deleted
555
556 \note This synchronous operation may require event handling, and so
557 it must not be called from the same thread as an EventHandler
558 (this is not a concern if asynchronous mode is enabled).
559
560 \sa startAsynchronousMode
561 */
562 bool removeEntry(const QString &id);
563
564Q_SIGNALS:
565 /**
566 Emitted when the KeyStore is changed
567
568 This occurs if entries are added, removed, or changed in this
569 KeyStore, including changes in entry availability.
570 */
571 void updated();
572
573 /**
574 Emitted when the KeyStore becomes unavailable
575 */
576 void unavailable();
577
578 /**
579 Emitted when an entry has been written, in asynchronous
580 mode.
581
582 \param entryId is the newly written entry id on success,
583 or an empty string if the write failed.
584 */
585 void entryWritten(const QString &entryId);
586
587 /**
588 Emitted when an entry has been removed, in asynchronous
589 mode.
590
591 \param success indicates if the removal succeeded (true) or not (false).
592 */
593 void entryRemoved(bool success);
594
595private:
596 Q_DISABLE_COPY(KeyStore)
597
598 friend class KeyStorePrivate;
599 KeyStorePrivate *d;
600
601 friend class KeyStoreManagerPrivate;
602};
603
604/**
605 \class KeyStoreInfo qca_keystore.h QtCrypto
606
607 Key store information, outside of a KeyStore object
608
609 This class is used in conjunction with the Event class,
610 and related classes such as PasswordAsker and TokenAsker,
611 to describe the key store source of the Event.
612
613 Each KeyStoreInfo represents a single KeyStore, and describes
614 the type of store (e.g. smartcard or PGP keyring - see
615 KeyStore::Type), and a couple of names. The id() of a KeyStore
616 is used to reference it, and is typically of the form
617 "qca-mystorename". The name() of a KeyStore is used to describe
618 it (i.e. this is the "pretty" name to show the user), and is
619 typically of the form "My Store Name".
620
621 \ingroup UserAPI
622*/
623class QCA_EXPORT KeyStoreInfo
624{
625public:
626 /**
627 Constructor.
628
629 \note This form of constructor for KeyStoreInfo
630 produces an object that does not describe any
631 KeyStore, and isNull() will return true.
632 */
633 KeyStoreInfo();
634
635 /**
636 Standard constructor.
637
638 This builds a KeyStoreInfo object that descibes a
639 KeyStore.
640
641 \param type the type of KeyStore
642 \param id the identification of the KeyStore
643 \param name the descriptive name of the KeyStore
644 */
645 KeyStoreInfo(KeyStore::Type type, const QString &id, const QString &name);
646
647 /**
648 Copy constructor.
649
650 \param from the KeyStoreInfo to copy from
651 */
652 KeyStoreInfo(const KeyStoreInfo &from);
653
654 ~KeyStoreInfo();
655
656 /**
657 Assignment operator.
658
659 \param from the KeyStoreInfo to copy from
660 */
661 KeyStoreInfo &operator=(const KeyStoreInfo &from);
662
663 /**
664 Test if this object is valid
665
666 \return true if the object is not valid
667 */
668 bool isNull() const;
669
670 /**
671 The Type of KeyStore that this KeyStoreInfo object
672 describes.
673 */
674 KeyStore::Type type() const;
675
676 /**
677 The unique identification of the KeyStore that
678 this KeyStoreInfo object describes.
679 */
680 QString id() const;
681
682 /**
683 The descriptive name of the KeyStore that this
684 KeyStoreInfo object describes.
685 */
686 QString name() const;
687
688private:
689 class Private;
690 QSharedDataPointer<Private> d;
691};
692
693/**
694 \class KeyStoreManager qca_keystore.h QtCrypto
695
696 Access keystores, and monitor keystores for changes.
697
698 Before you can access a KeyStore, you must create a
699 KeyStoreManager. You then need to start()
700 the KeyStoreManager, and either wait for the busyFinished()
701 signal, or block using waitForBusyFinished().
702
703 If you know the KeyStoreEntry that you need, you can
704 use KeyStore passively, as described in the KeyStoreEntry
705 documentation.
706
707 \ingroup UserAPI
708*/
709class QCA_EXPORT KeyStoreManager : public QObject
710{
711 Q_OBJECT
712public:
713 /**
714 Create a new KeyStoreManager
715
716 \param parent the parent for this object
717*/
718 KeyStoreManager(QObject *parent = nullptr);
719 ~KeyStoreManager() override;
720
721 /**
722 Initialize all key store providers
723 */
724 static void start();
725
726 /**
727 Initialize a specific key store provider
728
729 \param provider the name of the provider to start
730 */
731 static void start(const QString &provider);
732
733 /**
734 Indicates if the manager is busy looking for key stores
735 */
736 bool isBusy() const;
737
738 /**
739 Blocks until the manager is done looking for key stores
740 */
741 void waitForBusyFinished();
742
743 /**
744 A list of all the key stores
745 */
746 QStringList keyStores() const;
747
748 /**
749 The diagnostic result of key store operations, such as
750 warnings and errors
751 */
752 static QString diagnosticText();
753
754 /**
755 Clears the diagnostic result log
756 */
757 static void clearDiagnosticText();
758
759 /**
760 If you are not using the eventloop, call this to update
761 the object state to the present
762 */
763 void sync();
764
765Q_SIGNALS:
766 /**
767 emitted when the manager has started looking for key stores
768 */
769 void busyStarted();
770
771 /**
772 emitted when the manager has finished looking for key stores
773 */
774 void busyFinished();
775
776 /**
777 emitted when a new key store becomes available
778
779 \param id the name of the key store that has become available
780 */
781 void keyStoreAvailable(const QString &id);
782
783private:
784 Q_DISABLE_COPY(KeyStoreManager)
785
786 friend class KeyStoreManagerPrivate;
787 KeyStoreManagerPrivate *d;
788
789 friend class Global;
790 friend class KeyStorePrivate;
791
792 static void scan();
793 static void shutdown();
794};
795
796}
797
798#endif
799

source code of qca/include/QtCrypto/qca_keystore.h