• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
5 #ifndef NET_CERT_NSS_CERT_DATABASE_H_
6 #define NET_CERT_NSS_CERT_DATABASE_H_
7 
8 #include <string>
9 #include <vector>
10 
11 #include "base/basictypes.h"
12 #include "base/callback_forward.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/strings/string16.h"
16 #include "crypto/scoped_nss_types.h"
17 #include "net/base/net_errors.h"
18 #include "net/base/net_export.h"
19 #include "net/cert/cert_type.h"
20 #include "net/cert/x509_certificate.h"
21 
22 namespace base {
23 template <typename T> struct DefaultLazyInstanceTraits;
24 class TaskRunner;
25 }
26 template <class ObserverType> class ObserverListThreadSafe;
27 
28 namespace net {
29 
30 class CryptoModule;
31 typedef std::vector<scoped_refptr<CryptoModule> > CryptoModuleList;
32 
33 // Provides functions to manipulate the NSS certificate stores.
34 class NET_EXPORT NSSCertDatabase {
35  public:
36 
37   class NET_EXPORT Observer {
38    public:
~Observer()39     virtual ~Observer() {}
40 
41     // Will be called when a new certificate is added.
42     // Called with |cert| == NULL after importing a list of certificates
43     // in ImportFromPKCS12().
OnCertAdded(const X509Certificate * cert)44     virtual void OnCertAdded(const X509Certificate* cert) {}
45 
46     // Will be called when a certificate is removed.
OnCertRemoved(const X509Certificate * cert)47     virtual void OnCertRemoved(const X509Certificate* cert) {}
48 
49     // Will be called when a CA certificate is changed.
50     // Called with |cert| == NULL after importing a list of certificates
51     // in ImportCACerts().
OnCACertChanged(const X509Certificate * cert)52     virtual void OnCACertChanged(const X509Certificate* cert) {}
53 
54    protected:
Observer()55     Observer() {}
56 
57    private:
58     DISALLOW_COPY_AND_ASSIGN(Observer);
59   };
60 
61   // Stores per-certificate error codes for import failures.
62   struct NET_EXPORT ImportCertFailure {
63    public:
64     ImportCertFailure(const scoped_refptr<X509Certificate>& cert, int err);
65     ~ImportCertFailure();
66 
67     scoped_refptr<X509Certificate> certificate;
68     int net_error;
69   };
70   typedef std::vector<ImportCertFailure> ImportCertFailureList;
71 
72   // Constants that define which usages a certificate is trusted for.
73   // They are used in combination with CertType to specify trust for each type
74   // of certificate.
75   // For a CA_CERT, they specify that the CA is trusted for issuing server and
76   // client certs of each type.
77   // For SERVER_CERT, only TRUSTED_SSL makes sense, and specifies the cert is
78   // trusted as a server.
79   // For EMAIL_CERT, only TRUSTED_EMAIL makes sense, and specifies the cert is
80   // trusted for email.
81   // DISTRUSTED_* specifies that the cert should not be trusted for the given
82   // usage, regardless of whether it would otherwise inherit trust from the
83   // issuer chain.
84   // Use TRUST_DEFAULT to inherit trust as normal.
85   // NOTE: The actual constants are defined using an enum instead of static
86   // consts due to compilation/linkage constraints with template functions.
87   typedef uint32 TrustBits;
88   enum {
89     TRUST_DEFAULT         =      0,
90     TRUSTED_SSL           = 1 << 0,
91     TRUSTED_EMAIL         = 1 << 1,
92     TRUSTED_OBJ_SIGN      = 1 << 2,
93     DISTRUSTED_SSL        = 1 << 3,
94     DISTRUSTED_EMAIL      = 1 << 4,
95     DISTRUSTED_OBJ_SIGN   = 1 << 5,
96   };
97 
98   typedef base::Callback<void(scoped_ptr<CertificateList> certs)>
99       ListCertsCallback;
100 
101   typedef base::Callback<void(bool)> DeleteCertCallback;
102 
103   // DEPRECATED: See http://crbug.com/329735.
104   static NSSCertDatabase* GetInstance();
105 
106   // Get a list of unique certificates in the certificate database (one
107   // instance of all certificates).
108   // DEPRECATED by |ListCerts|. See http://crbug.com/340460.
109   virtual void ListCertsSync(CertificateList* certs);
110 
111   // Asynchronously get a list of unique certificates in the certificate
112   // database (one instance of all certificates). Note that the callback may be
113   // run even after the database is deleted.
114   virtual void ListCerts(const ListCertsCallback& callback);
115 
116   // Get a list of certificates in the certificate database of the given slot.
117   // Note that the callback may be run even after the database is deleted.
118   // Must be called on the IO thread and it calls |callback| on the IO thread.
119   // This does not block by retrieving the certs asynchronously on a worker
120   // thread. Never calls |callback| synchronously.
121   virtual void ListCertsInSlot(const ListCertsCallback& callback,
122                                PK11SlotInfo* slot);
123 
124   // Get the default slot for public key data.
125   virtual crypto::ScopedPK11Slot GetPublicSlot() const;
126 
127   // Get the default slot for private key or mixed private/public key data.
128   virtual crypto::ScopedPK11Slot GetPrivateSlot() const;
129 
130   // Get the default module for public key data.
131   // The returned pointer must be stored in a scoped_refptr<CryptoModule>.
132   // DEPRECATED: use GetPublicSlot instead.
133   // TODO(mattm): remove usage of this method and remove it.
134   CryptoModule* GetPublicModule() const;
135 
136   // Get the default module for private key or mixed private/public key data.
137   // The returned pointer must be stored in a scoped_refptr<CryptoModule>.
138   // DEPRECATED: use GetPrivateSlot instead.
139   // TODO(mattm): remove usage of this method and remove it.
140   CryptoModule* GetPrivateModule() const;
141 
142   // Get all modules.
143   // If |need_rw| is true, only writable modules will be returned.
144   // TODO(mattm): come up with better alternative to CryptoModuleList.
145   virtual void ListModules(CryptoModuleList* modules, bool need_rw) const;
146 
147   // Import certificates and private keys from PKCS #12 blob into the module.
148   // If |is_extractable| is false, mark the private key as being unextractable
149   // from the module.
150   // Returns OK or a network error code such as ERR_PKCS12_IMPORT_BAD_PASSWORD
151   // or ERR_PKCS12_IMPORT_ERROR. |imported_certs|, if non-NULL, returns a list
152   // of certs that were imported.
153   int ImportFromPKCS12(CryptoModule* module,
154                        const std::string& data,
155                        const base::string16& password,
156                        bool is_extractable,
157                        CertificateList* imported_certs);
158 
159   // Export the given certificates and private keys into a PKCS #12 blob,
160   // storing into |output|.
161   // Returns the number of certificates successfully exported.
162   int ExportToPKCS12(const CertificateList& certs,
163                      const base::string16& password,
164                      std::string* output) const;
165 
166   // Uses similar logic to nsNSSCertificateDB::handleCACertDownload to find the
167   // root.  Assumes the list is an ordered hierarchy with the root being either
168   // the first or last element.
169   // TODO(mattm): improve this to handle any order.
170   X509Certificate* FindRootInList(const CertificateList& certificates) const;
171 
172   // Import CA certificates.
173   // Tries to import all the certificates given.  The root will be trusted
174   // according to |trust_bits|.  Any certificates that could not be imported
175   // will be listed in |not_imported|.
176   // Returns false if there is an internal error, otherwise true is returned and
177   // |not_imported| should be checked for any certificates that were not
178   // imported.
179   bool ImportCACerts(const CertificateList& certificates,
180                      TrustBits trust_bits,
181                      ImportCertFailureList* not_imported);
182 
183   // Import server certificate.  The first cert should be the server cert.  Any
184   // additional certs should be intermediate/CA certs and will be imported but
185   // not given any trust.
186   // Any certificates that could not be imported will be listed in
187   // |not_imported|.
188   // |trust_bits| can be set to explicitly trust or distrust the certificate, or
189   // use TRUST_DEFAULT to inherit trust as normal.
190   // Returns false if there is an internal error, otherwise true is returned and
191   // |not_imported| should be checked for any certificates that were not
192   // imported.
193   bool ImportServerCert(const CertificateList& certificates,
194                         TrustBits trust_bits,
195                         ImportCertFailureList* not_imported);
196 
197   // Get trust bits for certificate.
198   TrustBits GetCertTrust(const X509Certificate* cert, CertType type) const;
199 
200   // IsUntrusted returns true if |cert| is specifically untrusted. These
201   // certificates are stored in the database for the specific purpose of
202   // rejecting them.
203   bool IsUntrusted(const X509Certificate* cert) const;
204 
205   // Set trust values for certificate.
206   // Returns true on success or false on failure.
207   bool SetCertTrust(const X509Certificate* cert,
208                     CertType type,
209                     TrustBits trust_bits);
210 
211   // Delete certificate and associated private key (if one exists).
212   // |cert| is still valid when this function returns. Returns true on
213   // success.
214   bool DeleteCertAndKey(X509Certificate* cert);
215 
216   // Like DeleteCertAndKey but does not block by running the removal on a worker
217   // thread. This must be called on IO thread and it will run |callback| on IO
218   // thread. Never calls |callback| synchronously.
219   void DeleteCertAndKeyAsync(const scoped_refptr<X509Certificate>& cert,
220                              const DeleteCertCallback& callback);
221 
222   // Check whether cert is stored in a readonly slot.
223   bool IsReadOnly(const X509Certificate* cert) const;
224 
225   // Check whether cert is stored in a hardware slot.
226   bool IsHardwareBacked(const X509Certificate* cert) const;
227 
228   // Registers |observer| to receive notifications of certificate changes.  The
229   // thread on which this is called is the thread on which |observer| will be
230   // called back with notifications.
231   // NOTE: CertDatabase::AddObserver should be preferred. Observers registered
232   // here will only receive notifications generated directly through the
233   // NSSCertDatabase, but not those from the CertDatabase. The CertDatabase
234   // observers will receive both.
235   void AddObserver(Observer* observer);
236 
237   // Unregisters |observer| from receiving notifications.  This must be called
238   // on the same thread on which AddObserver() was called.
239   void RemoveObserver(Observer* observer);
240 
241   // Overrides task runner that's used for running slow tasks.
242   void SetSlowTaskRunnerForTest(
243       const scoped_refptr<base::TaskRunner>& task_runner);
244 
245  protected:
246   NSSCertDatabase();
247   virtual ~NSSCertDatabase();
248 
249   // Certificate listing implementation used by |ListCerts*| and
250   // |ListCertsSync|. Static so it may safely be used on the worker thread.
251   // If |slot| is NULL, obtains the certs of all slots, otherwise only of
252   // |slot|.
253   static void ListCertsImpl(crypto::ScopedPK11Slot slot,
254                             CertificateList* certs);
255 
256   // Gets task runner that should be used for slow tasks like certificate
257   // listing. Defaults to a base::WorkerPool runner, but may be overriden
258   // in tests (see SetSlowTaskRunnerForTest).
259   scoped_refptr<base::TaskRunner> GetSlowTaskRunner() const;
260 
261  private:
262   friend struct base::DefaultLazyInstanceTraits<NSSCertDatabase>;
263 
264   // Notifies observers of the removal of |cert| and calls |callback| with
265   // |success| as argument.
266   void NotifyCertRemovalAndCallBack(scoped_refptr<X509Certificate> cert,
267                                     const DeleteCertCallback& callback,
268                                     bool success);
269 
270   // Broadcasts notifications to all registered observers.
271   void NotifyObserversOfCertAdded(const X509Certificate* cert);
272   void NotifyObserversOfCertRemoved(const X509Certificate* cert);
273   void NotifyObserversOfCACertChanged(const X509Certificate* cert);
274 
275   // Certificate removal implementation used by |DeleteCertAndKey*|. Static so
276   // it may safely be used on the worker thread.
277   static bool DeleteCertAndKeyImpl(scoped_refptr<X509Certificate> cert);
278 
279   // Task runner that should be used in tests if set.
280   scoped_refptr<base::TaskRunner> slow_task_runner_for_test_;
281 
282   const scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_;
283 
284   base::WeakPtrFactory<NSSCertDatabase> weak_factory_;
285 
286   DISALLOW_COPY_AND_ASSIGN(NSSCertDatabase);
287 };
288 
289 }  // namespace net
290 
291 #endif  // NET_CERT_NSS_CERT_DATABASE_H_
292