nss_cert_database.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef NET_CERT_NSS_CERT_DATABASE_H_
  5. #define NET_CERT_NSS_CERT_DATABASE_H_
  6. #include <stdint.h>
  7. #include <memory>
  8. #include <string>
  9. #include <vector>
  10. #include "base/callback_forward.h"
  11. #include "base/memory/ref_counted.h"
  12. #include "base/memory/weak_ptr.h"
  13. #include "build/build_config.h"
  14. #include "build/chromeos_buildflags.h"
  15. #include "crypto/scoped_nss_types.h"
  16. #include "net/base/net_errors.h"
  17. #include "net/base/net_export.h"
  18. #include "net/cert/cert_type.h"
  19. #include "net/cert/scoped_nss_types.h"
  20. #include "net/cert/x509_certificate.h"
  21. namespace base {
  22. template <class ObserverType>
  23. class ObserverListThreadSafe;
  24. }
  25. namespace net {
  26. // Provides functions to manipulate the NSS certificate stores.
  27. // Forwards notifications about certificate changes to the global CertDatabase
  28. // singleton.
  29. class NET_EXPORT NSSCertDatabase {
  30. public:
  31. class NET_EXPORT Observer {
  32. public:
  33. Observer(const Observer&) = delete;
  34. Observer& operator=(const Observer&) = delete;
  35. virtual ~Observer() = default;
  36. // Will be called when a certificate is added, removed, or trust settings
  37. // are changed.
  38. virtual void OnCertDBChanged() {}
  39. protected:
  40. Observer() = default;
  41. };
  42. // Holds an NSS certificate along with additional information.
  43. struct CertInfo {
  44. CertInfo();
  45. CertInfo(CertInfo&& other);
  46. ~CertInfo();
  47. CertInfo& operator=(CertInfo&& other);
  48. // The certificate itself.
  49. ScopedCERTCertificate cert;
  50. // The certificate is stored on a read-only slot.
  51. bool on_read_only_slot = false;
  52. // The certificate is untrusted.
  53. bool untrusted = false;
  54. // The certificate is trusted for web navigations according to the trust
  55. // bits stored in the database.
  56. bool web_trust_anchor = false;
  57. // The certificate is hardware-backed.
  58. bool hardware_backed = false;
  59. // The certificate is device-wide.
  60. // Note: can be true only on Chrome OS.
  61. bool device_wide = false;
  62. };
  63. // Stores per-certificate error codes for import failures.
  64. struct NET_EXPORT ImportCertFailure {
  65. public:
  66. ImportCertFailure(ScopedCERTCertificate cert, int err);
  67. ImportCertFailure(ImportCertFailure&& other);
  68. ~ImportCertFailure();
  69. ScopedCERTCertificate certificate;
  70. int net_error;
  71. };
  72. typedef std::vector<ImportCertFailure> ImportCertFailureList;
  73. // Constants that define which usages a certificate is trusted for.
  74. // They are used in combination with CertType to specify trust for each type
  75. // of certificate.
  76. // For a CA_CERT, they specify that the CA is trusted for issuing server and
  77. // client certs of each type.
  78. // For SERVER_CERT, only TRUSTED_SSL makes sense, and specifies the cert is
  79. // trusted as a server.
  80. // For EMAIL_CERT, only TRUSTED_EMAIL makes sense, and specifies the cert is
  81. // trusted for email.
  82. // DISTRUSTED_* specifies that the cert should not be trusted for the given
  83. // usage, regardless of whether it would otherwise inherit trust from the
  84. // issuer chain.
  85. // Use TRUST_DEFAULT to inherit trust as normal.
  86. // NOTE: The actual constants are defined using an enum instead of static
  87. // consts due to compilation/linkage constraints with template functions.
  88. typedef uint32_t TrustBits;
  89. enum {
  90. TRUST_DEFAULT = 0,
  91. TRUSTED_SSL = 1 << 0,
  92. TRUSTED_EMAIL = 1 << 1,
  93. TRUSTED_OBJ_SIGN = 1 << 2,
  94. DISTRUSTED_SSL = 1 << 3,
  95. DISTRUSTED_EMAIL = 1 << 4,
  96. DISTRUSTED_OBJ_SIGN = 1 << 5,
  97. };
  98. using CertInfoList = std::vector<CertInfo>;
  99. using ListCertsInfoCallback =
  100. base::OnceCallback<void(CertInfoList certs_info)>;
  101. using ListCertsCallback =
  102. base::OnceCallback<void(ScopedCERTCertificateList certs)>;
  103. using DeleteCertCallback = base::OnceCallback<void(bool)>;
  104. // Creates a NSSCertDatabase that will store public information (such as
  105. // certificates and trust records) in |public_slot|, and private information
  106. // (such as keys) in |private_slot|.
  107. // In general, code should avoid creating an NSSCertDatabase directly,
  108. // as doing so requires making opinionated decisions about where to store
  109. // data, and instead prefer to be passed an existing NSSCertDatabase
  110. // instance.
  111. // |public_slot| must not be NULL, |private_slot| can be NULL. Both slots can
  112. // be identical.
  113. NSSCertDatabase(crypto::ScopedPK11Slot public_slot,
  114. crypto::ScopedPK11Slot private_slot);
  115. NSSCertDatabase(const NSSCertDatabase&) = delete;
  116. NSSCertDatabase& operator=(const NSSCertDatabase&) = delete;
  117. virtual ~NSSCertDatabase();
  118. // Asynchronously get a list of unique certificates in the certificate
  119. // database (one instance of all certificates). Note that the callback may be
  120. // run even after the database is deleted.
  121. virtual void ListCerts(ListCertsCallback callback);
  122. // Get a list of certificates in the certificate database of the given slot.
  123. // Note that the callback may be run even after the database is deleted. Must
  124. // be called on the IO thread. This does not block by retrieving the certs
  125. // asynchronously on a worker thread.
  126. virtual void ListCertsInSlot(ListCertsCallback callback, PK11SlotInfo* slot);
  127. // Asynchronously get a list of certificates along with additional
  128. // information. Note that the callback may be run even after the database is
  129. // deleted.
  130. virtual void ListCertsInfo(ListCertsInfoCallback callback);
  131. #if BUILDFLAG(IS_CHROMEOS)
  132. // Get the slot for system-wide key data. May be NULL if the system token was
  133. // not enabled for this database.
  134. virtual crypto::ScopedPK11Slot GetSystemSlot() const;
  135. // Checks whether |cert| is stored on |slot|.
  136. static bool IsCertificateOnSlot(CERTCertificate* cert, PK11SlotInfo* slot);
  137. #endif // BUILDFLAG(IS_CHROMEOS)
  138. // Get the default slot for public key data.
  139. crypto::ScopedPK11Slot GetPublicSlot() const;
  140. // Get the default slot for private key or mixed private/public key data.
  141. // Can return NULL.
  142. crypto::ScopedPK11Slot GetPrivateSlot() const;
  143. // Get all modules.
  144. // If |need_rw| is true, only writable modules will be returned.
  145. virtual void ListModules(std::vector<crypto::ScopedPK11Slot>* modules,
  146. bool need_rw) const;
  147. // Set trust values for certificate.
  148. // Returns true on success or false on failure.
  149. virtual bool SetCertTrust(CERTCertificate* cert,
  150. CertType type,
  151. TrustBits trust_bits);
  152. // Import certificates and private keys from PKCS #12 blob into the module.
  153. // If |is_extractable| is false, mark the private key as being unextractable
  154. // from the module.
  155. // Returns OK or a network error code such as ERR_PKCS12_IMPORT_BAD_PASSWORD
  156. // or ERR_PKCS12_IMPORT_ERROR. |imported_certs|, if non-NULL, returns a list
  157. // of certs that were imported.
  158. int ImportFromPKCS12(PK11SlotInfo* slot_info,
  159. const std::string& data,
  160. const std::u16string& password,
  161. bool is_extractable,
  162. ScopedCERTCertificateList* imported_certs);
  163. // Export the given certificates and private keys into a PKCS #12 blob,
  164. // storing into |output|.
  165. // Returns the number of certificates successfully exported.
  166. int ExportToPKCS12(const ScopedCERTCertificateList& certs,
  167. const std::u16string& password,
  168. std::string* output) const;
  169. // Uses similar logic to nsNSSCertificateDB::handleCACertDownload to find the
  170. // root. Assumes the list is an ordered hierarchy with the root being either
  171. // the first or last element.
  172. // TODO(mattm): improve this to handle any order.
  173. CERTCertificate* FindRootInList(
  174. const ScopedCERTCertificateList& certificates) const;
  175. // Import a user certificate. The private key for the user certificate must
  176. // already be installed, otherwise we return ERR_NO_PRIVATE_KEY_FOR_CERT.
  177. // Returns OK or a network error code.
  178. int ImportUserCert(const std::string& data);
  179. int ImportUserCert(CERTCertificate* cert);
  180. // Import CA certificates.
  181. // Tries to import all the certificates given. The root will be trusted
  182. // according to |trust_bits|. Any certificates that could not be imported
  183. // will be listed in |not_imported|.
  184. // Returns false if there is an internal error, otherwise true is returned and
  185. // |not_imported| should be checked for any certificates that were not
  186. // imported.
  187. bool ImportCACerts(const ScopedCERTCertificateList& certificates,
  188. TrustBits trust_bits,
  189. ImportCertFailureList* not_imported);
  190. // Import server certificate. The first cert should be the server cert. Any
  191. // additional certs should be intermediate/CA certs and will be imported but
  192. // not given any trust.
  193. // Any certificates that could not be imported will be listed in
  194. // |not_imported|.
  195. // |trust_bits| can be set to explicitly trust or distrust the certificate, or
  196. // use TRUST_DEFAULT to inherit trust as normal.
  197. // Returns false if there is an internal error, otherwise true is returned and
  198. // |not_imported| should be checked for any certificates that were not
  199. // imported.
  200. bool ImportServerCert(const ScopedCERTCertificateList& certificates,
  201. TrustBits trust_bits,
  202. ImportCertFailureList* not_imported);
  203. // Get trust bits for certificate.
  204. TrustBits GetCertTrust(const CERTCertificate* cert, CertType type) const;
  205. // Delete certificate and associated private key (if one exists).
  206. // |cert| is still valid when this function returns. Returns true on
  207. // success.
  208. bool DeleteCertAndKey(CERTCertificate* cert);
  209. // Like DeleteCertAndKey but does not block by running the removal on a worker
  210. // thread. This must be called on IO thread and it will run |callback| on IO
  211. // thread. Never calls |callback| synchronously.
  212. void DeleteCertAndKeyAsync(ScopedCERTCertificate cert,
  213. DeleteCertCallback callback);
  214. // IsUntrusted returns true if |cert| is specifically untrusted. These
  215. // certificates are stored in the database for the specific purpose of
  216. // rejecting them.
  217. static bool IsUntrusted(const CERTCertificate* cert);
  218. // IsWebTrustAnchor returns true if |cert| is explicitly trusted for web
  219. // navigations according to the trust bits stored in the database.
  220. static bool IsWebTrustAnchor(const CERTCertificate* cert);
  221. // Check whether cert is stored in a readonly slot.
  222. static bool IsReadOnly(const CERTCertificate* cert);
  223. // Check whether cert is stored in a hardware slot.
  224. // This should only be invoked on a worker thread due to expensive operations
  225. // behind it.
  226. static bool IsHardwareBacked(const CERTCertificate* cert);
  227. // Registers |observer| to receive notifications of certificate changes. The
  228. // thread on which this is called is the thread on which |observer| will be
  229. // called back with notifications.
  230. // NOTE: Observers registered here will only receive notifications generated
  231. // directly through the NSSCertDatabase, but not those from the CertDatabase.
  232. // CertDatabase observers will receive all certificate notifications.
  233. void AddObserver(Observer* observer);
  234. // Unregisters |observer| from receiving notifications. This must be called
  235. // on the same thread on which AddObserver() was called.
  236. void RemoveObserver(Observer* observer);
  237. protected:
  238. // Returns a list of certificates extracted from |certs_info| list ignoring
  239. // additional information.
  240. static ScopedCERTCertificateList ExtractCertificates(CertInfoList certs_info);
  241. // Certificate listing implementation used by |ListCerts*|. Static so it may
  242. // safely be used on the worker thread. If |slot| is nullptr, obtains the
  243. // certs of all slots, otherwise only of |slot|.
  244. static ScopedCERTCertificateList ListCertsImpl(crypto::ScopedPK11Slot slot);
  245. // Implements the logic behind returning a list of certificates along with
  246. // additional information about every certificate.
  247. // If |add_certs_info| is false, doesn't compute the certificate additional
  248. // information, the corresponding CertInfo struct fields will be left on their
  249. // default values.
  250. // Static so it may safely be used on the worker thread. If |slot| is nullptr,
  251. // obtains the certs of all slots, otherwise only of |slot|.
  252. static CertInfoList ListCertsInfoImpl(crypto::ScopedPK11Slot slot,
  253. bool add_certs_info);
  254. // Broadcasts notifications to all registered observers.
  255. void NotifyObserversCertDBChanged();
  256. private:
  257. // Notifies observers of the removal of a cert and calls |callback| with
  258. // |success| as argument.
  259. void NotifyCertRemovalAndCallBack(DeleteCertCallback callback, bool success);
  260. // Certificate removal implementation used by |DeleteCertAndKey*|. Static so
  261. // it may safely be used on the worker thread.
  262. static bool DeleteCertAndKeyImpl(CERTCertificate* cert);
  263. // Like above, but taking a ScopedCERTCertificate. This is a workaround for
  264. // base::Bind not having a way to own a unique_ptr but pass it to the
  265. // function as a raw pointer.
  266. static bool DeleteCertAndKeyImplScoped(ScopedCERTCertificate cert);
  267. crypto::ScopedPK11Slot public_slot_;
  268. crypto::ScopedPK11Slot private_slot_;
  269. // A helper observer that forwards events from this database to CertDatabase.
  270. std::unique_ptr<Observer> cert_notification_forwarder_;
  271. const scoped_refptr<base::ObserverListThreadSafe<Observer>> observer_list_;
  272. base::WeakPtrFactory<NSSCertDatabase> weak_factory_{this};
  273. };
  274. } // namespace net
  275. #endif // NET_CERT_NSS_CERT_DATABASE_H_