nss_util.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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#include "crypto/nss_util.h"
6#include "crypto/nss_util_internal.h"
7
8#include <nss.h>
9#include <pk11pub.h>
10#include <plarena.h>
11#include <prerror.h>
12#include <prinit.h>
13#include <prtime.h>
14#include <secmod.h>
15
16#if defined(OS_OPENBSD)
17#include <sys/mount.h>
18#include <sys/param.h>
19#endif
20
21#include <map>
22#include <vector>
23
24#include "base/base_paths.h"
25#include "base/bind.h"
26#include "base/cpu.h"
27#include "base/debug/alias.h"
28#include "base/debug/stack_trace.h"
29#include "base/environment.h"
30#include "base/file_util.h"
31#include "base/files/file_path.h"
32#include "base/lazy_instance.h"
33#include "base/logging.h"
34#include "base/memory/scoped_ptr.h"
35#include "base/message_loop/message_loop.h"
36#include "base/metrics/histogram.h"
37#include "base/native_library.h"
38#include "base/path_service.h"
39#include "base/stl_util.h"
40#include "base/strings/stringprintf.h"
41#include "base/threading/thread_checker.h"
42#include "base/threading/thread_restrictions.h"
43#include "base/threading/worker_pool.h"
44#include "build/build_config.h"
45
46// USE_NSS means we use NSS for everything crypto-related.  If USE_NSS is not
47// defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
48// use NSS for crypto or certificate verification, and we don't use the NSS
49// certificate and key databases.
50#if defined(USE_NSS)
51#include "base/synchronization/lock.h"
52#include "crypto/nss_crypto_module_delegate.h"
53#endif  // defined(USE_NSS)
54
55namespace crypto {
56
57namespace {
58
59#if defined(OS_CHROMEOS)
60const char kUserNSSDatabaseName[] = "UserNSSDB";
61
62// Constants for loading the Chrome OS TPM-backed PKCS #11 library.
63const char kChapsModuleName[] = "Chaps";
64const char kChapsPath[] = "libchaps.so";
65
66// Fake certificate authority database used for testing.
67static const base::FilePath::CharType kReadOnlyCertDB[] =
68    FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
69#endif  // defined(OS_CHROMEOS)
70
71std::string GetNSSErrorMessage() {
72  std::string result;
73  if (PR_GetErrorTextLength()) {
74    scoped_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
75    PRInt32 copied = PR_GetErrorText(error_text.get());
76    result = std::string(error_text.get(), copied);
77  } else {
78    result = base::StringPrintf("NSS error code: %d", PR_GetError());
79  }
80  return result;
81}
82
83#if defined(USE_NSS)
84#if !defined(OS_CHROMEOS)
85base::FilePath GetDefaultConfigDirectory() {
86  base::FilePath dir;
87  PathService::Get(base::DIR_HOME, &dir);
88  if (dir.empty()) {
89    LOG(ERROR) << "Failed to get home directory.";
90    return dir;
91  }
92  dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
93  if (!base::CreateDirectory(dir)) {
94    LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
95    dir.clear();
96  }
97  DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
98  return dir;
99}
100#endif  // !defined(IS_CHROMEOS)
101
102// On non-Chrome OS platforms, return the default config directory. On Chrome OS
103// test images, return a read-only directory with fake root CA certs (which are
104// used by the local Google Accounts server mock we use when testing our login
105// code). On Chrome OS non-test images (where the read-only directory doesn't
106// exist), return an empty path.
107base::FilePath GetInitialConfigDirectory() {
108#if defined(OS_CHROMEOS)
109  base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
110  if (!base::PathExists(database_dir))
111    database_dir.clear();
112  return database_dir;
113#else
114  return GetDefaultConfigDirectory();
115#endif  // defined(OS_CHROMEOS)
116}
117
118// This callback for NSS forwards all requests to a caller-specified
119// CryptoModuleBlockingPasswordDelegate object.
120char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
121  crypto::CryptoModuleBlockingPasswordDelegate* delegate =
122      reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
123  if (delegate) {
124    bool cancelled = false;
125    std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
126                                                     retry != PR_FALSE,
127                                                     &cancelled);
128    if (cancelled)
129      return NULL;
130    char* result = PORT_Strdup(password.c_str());
131    password.replace(0, password.size(), password.size(), 0);
132    return result;
133  }
134  DLOG(ERROR) << "PK11 password requested with NULL arg";
135  return NULL;
136}
137
138// NSS creates a local cache of the sqlite database if it detects that the
139// filesystem the database is on is much slower than the local disk.  The
140// detection doesn't work with the latest versions of sqlite, such as 3.6.22
141// (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561).  So we set
142// the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
143// detection when database_dir is on NFS.  See http://crbug.com/48585.
144//
145// TODO(wtc): port this function to other USE_NSS platforms.  It is defined
146// only for OS_LINUX and OS_OPENBSD simply because the statfs structure
147// is OS-specific.
148//
149// Because this function sets an environment variable it must be run before we
150// go multi-threaded.
151void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) {
152  bool db_on_nfs = false;
153#if defined(OS_LINUX)
154  base::FileSystemType fs_type = base::FILE_SYSTEM_UNKNOWN;
155  if (base::GetFileSystemType(database_dir, &fs_type))
156    db_on_nfs = (fs_type == base::FILE_SYSTEM_NFS);
157#elif defined(OS_OPENBSD)
158  struct statfs buf;
159  if (statfs(database_dir.value().c_str(), &buf) == 0)
160    db_on_nfs = (strcmp(buf.f_fstypename, MOUNT_NFS) == 0);
161#else
162  NOTIMPLEMENTED();
163#endif
164
165  if (db_on_nfs) {
166    scoped_ptr<base::Environment> env(base::Environment::Create());
167    static const char kUseCacheEnvVar[] = "NSS_SDB_USE_CACHE";
168    if (!env->HasVar(kUseCacheEnvVar))
169      env->SetVar(kUseCacheEnvVar, "yes");
170  }
171}
172
173#endif  // defined(USE_NSS)
174
175// A singleton to initialize/deinitialize NSPR.
176// Separate from the NSS singleton because we initialize NSPR on the UI thread.
177// Now that we're leaking the singleton, we could merge back with the NSS
178// singleton.
179class NSPRInitSingleton {
180 private:
181  friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
182
183  NSPRInitSingleton() {
184    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
185  }
186
187  // NOTE(willchan): We don't actually execute this code since we leak NSS to
188  // prevent non-joinable threads from using NSS after it's already been shut
189  // down.
190  ~NSPRInitSingleton() {
191    PL_ArenaFinish();
192    PRStatus prstatus = PR_Cleanup();
193    if (prstatus != PR_SUCCESS)
194      LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
195  }
196};
197
198base::LazyInstance<NSPRInitSingleton>::Leaky
199    g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
200
201// This is a LazyInstance so that it will be deleted automatically when the
202// unittest exits.  NSSInitSingleton is a LeakySingleton, so it would not be
203// deleted if it were a regular member.
204base::LazyInstance<base::ScopedTempDir> g_test_nss_db_dir =
205    LAZY_INSTANCE_INITIALIZER;
206
207// Force a crash with error info on NSS_NoDB_Init failure.
208void CrashOnNSSInitFailure() {
209  int nss_error = PR_GetError();
210  int os_error = PR_GetOSError();
211  base::debug::Alias(&nss_error);
212  base::debug::Alias(&os_error);
213  LOG(ERROR) << "Error initializing NSS without a persistent database: "
214             << GetNSSErrorMessage();
215  LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
216}
217
218#if defined(OS_CHROMEOS)
219class ChromeOSUserData {
220 public:
221  explicit ChromeOSUserData(ScopedPK11Slot public_slot)
222      : public_slot_(public_slot.Pass()),
223        private_slot_initialization_started_(false) {}
224  ~ChromeOSUserData() {
225    if (public_slot_) {
226      SECStatus status = SECMOD_CloseUserDB(public_slot_.get());
227      if (status != SECSuccess)
228        PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
229    }
230  }
231
232  ScopedPK11Slot GetPublicSlot() {
233    return ScopedPK11Slot(
234        public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL);
235  }
236
237  ScopedPK11Slot GetPrivateSlot(
238      const base::Callback<void(ScopedPK11Slot)>& callback) {
239    if (private_slot_)
240      return ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get()));
241    if (!callback.is_null())
242      tpm_ready_callback_list_.push_back(callback);
243    return ScopedPK11Slot();
244  }
245
246  void SetPrivateSlot(ScopedPK11Slot private_slot) {
247    DCHECK(!private_slot_);
248    private_slot_ = private_slot.Pass();
249
250    SlotReadyCallbackList callback_list;
251    callback_list.swap(tpm_ready_callback_list_);
252    for (SlotReadyCallbackList::iterator i = callback_list.begin();
253         i != callback_list.end();
254         ++i) {
255      (*i).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get())));
256    }
257  }
258
259  bool private_slot_initialization_started() const {
260      return private_slot_initialization_started_;
261  }
262
263  void set_private_slot_initialization_started() {
264      private_slot_initialization_started_ = true;
265  }
266
267 private:
268  ScopedPK11Slot public_slot_;
269  ScopedPK11Slot private_slot_;
270
271  bool private_slot_initialization_started_;
272
273  typedef std::vector<base::Callback<void(ScopedPK11Slot)> >
274      SlotReadyCallbackList;
275  SlotReadyCallbackList tpm_ready_callback_list_;
276};
277#endif  // defined(OS_CHROMEOS)
278
279class NSSInitSingleton {
280 public:
281#if defined(OS_CHROMEOS)
282  // Used with PostTaskAndReply to pass handles to worker thread and back.
283  struct TPMModuleAndSlot {
284    explicit TPMModuleAndSlot(SECMODModule* init_chaps_module)
285        : chaps_module(init_chaps_module), tpm_slot(NULL) {}
286    SECMODModule* chaps_module;
287    PK11SlotInfo* tpm_slot;
288  };
289
290  PK11SlotInfo* OpenPersistentNSSDBForPath(const std::string& db_name,
291                                           const base::FilePath& path) {
292    DCHECK(thread_checker_.CalledOnValidThread());
293    // NSS is allowed to do IO on the current thread since dispatching
294    // to a dedicated thread would still have the affect of blocking
295    // the current thread, due to NSS's internal locking requirements
296    base::ThreadRestrictions::ScopedAllowIO allow_io;
297
298    base::FilePath nssdb_path = path.AppendASCII(".pki").AppendASCII("nssdb");
299    if (!base::CreateDirectory(nssdb_path)) {
300      LOG(ERROR) << "Failed to create " << nssdb_path.value() << " directory.";
301      return NULL;
302    }
303    return OpenUserDB(nssdb_path, db_name);
304  }
305
306  void EnableTPMTokenForNSS() {
307    DCHECK(thread_checker_.CalledOnValidThread());
308
309    // If this gets set, then we'll use the TPM for certs with
310    // private keys, otherwise we'll fall back to the software
311    // implementation.
312    tpm_token_enabled_for_nss_ = true;
313  }
314
315  bool IsTPMTokenEnabledForNSS() {
316    DCHECK(thread_checker_.CalledOnValidThread());
317    return tpm_token_enabled_for_nss_;
318  }
319
320  void InitializeTPMTokenAndSystemSlot(
321      int system_slot_id,
322      const base::Callback<void(bool)>& callback) {
323    DCHECK(thread_checker_.CalledOnValidThread());
324    // Should not be called while there is already an initialization in
325    // progress.
326    DCHECK(!initializing_tpm_token_);
327    // If EnableTPMTokenForNSS hasn't been called, return false.
328    if (!tpm_token_enabled_for_nss_) {
329      base::MessageLoop::current()->PostTask(FROM_HERE,
330                                             base::Bind(callback, false));
331      return;
332    }
333
334    // If everything is already initialized, then return true.
335    // Note that only |tpm_slot_| is checked, since |chaps_module_| could be
336    // NULL in tests while |tpm_slot_| has been set to the test DB.
337    if (tpm_slot_) {
338      base::MessageLoop::current()->PostTask(FROM_HERE,
339                                             base::Bind(callback, true));
340      return;
341    }
342
343    // Note that a reference is not taken to chaps_module_. This is safe since
344    // NSSInitSingleton is Leaky, so the reference it holds is never released.
345    scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
346    TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
347    if (base::WorkerPool::PostTaskAndReply(
348            FROM_HERE,
349            base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
350                       system_slot_id,
351                       tpm_args_ptr),
352            base::Bind(&NSSInitSingleton::OnInitializedTPMTokenAndSystemSlot,
353                       base::Unretained(this),  // NSSInitSingleton is leaky
354                       callback,
355                       base::Passed(&tpm_args)),
356            true /* task_is_slow */
357            )) {
358      initializing_tpm_token_ = true;
359    } else {
360      base::MessageLoop::current()->PostTask(FROM_HERE,
361                                             base::Bind(callback, false));
362    }
363  }
364
365  static void InitializeTPMTokenOnWorkerThread(CK_SLOT_ID token_slot_id,
366                                               TPMModuleAndSlot* tpm_args) {
367    // This tries to load the Chaps module so NSS can talk to the hardware
368    // TPM.
369    if (!tpm_args->chaps_module) {
370      DVLOG(3) << "Loading chaps...";
371      tpm_args->chaps_module = LoadModule(
372          kChapsModuleName,
373          kChapsPath,
374          // For more details on these parameters, see:
375          // https://developer.mozilla.org/en/PKCS11_Module_Specs
376          // slotFlags=[PublicCerts] -- Certificates and public keys can be
377          //   read from this slot without requiring a call to C_Login.
378          // askpw=only -- Only authenticate to the token when necessary.
379          "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
380    }
381    if (tpm_args->chaps_module) {
382      tpm_args->tpm_slot =
383          GetTPMSlotForIdOnWorkerThread(tpm_args->chaps_module, token_slot_id);
384    }
385  }
386
387  void OnInitializedTPMTokenAndSystemSlot(
388      const base::Callback<void(bool)>& callback,
389      scoped_ptr<TPMModuleAndSlot> tpm_args) {
390    DCHECK(thread_checker_.CalledOnValidThread());
391    DVLOG(2) << "Loaded chaps: " << !!tpm_args->chaps_module
392             << ", got tpm slot: " << !!tpm_args->tpm_slot;
393
394    chaps_module_ = tpm_args->chaps_module;
395    tpm_slot_ = tpm_args->tpm_slot;
396    if (!chaps_module_ && test_slot_) {
397      // chromeos_unittests try to test the TPM initialization process. If we
398      // have a test DB open, pretend that it is the TPM slot.
399      tpm_slot_ = PK11_ReferenceSlot(test_slot_);
400    }
401    initializing_tpm_token_ = false;
402
403    if (tpm_slot_) {
404      TPMReadyCallbackList callback_list;
405      callback_list.swap(tpm_ready_callback_list_);
406      for (TPMReadyCallbackList::iterator i = callback_list.begin();
407           i != callback_list.end();
408           ++i) {
409        (*i).Run();
410      }
411    }
412
413    callback.Run(!!tpm_slot_);
414  }
415
416  bool IsTPMTokenReady(const base::Closure& callback) {
417    if (!callback.is_null()) {
418      // Cannot DCHECK in the general case yet, but since the callback is
419      // a new addition to the API, DCHECK to make sure at least the new uses
420      // don't regress.
421      DCHECK(thread_checker_.CalledOnValidThread());
422    } else if (!thread_checker_.CalledOnValidThread()) {
423      // TODO(mattm): Change to DCHECK when callers have been fixed.
424      DVLOG(1) << "Called on wrong thread.\n"
425               << base::debug::StackTrace().ToString();
426    }
427
428    if (tpm_slot_ != NULL)
429      return true;
430
431    if (!callback.is_null())
432      tpm_ready_callback_list_.push_back(callback);
433
434    return false;
435  }
436
437  // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
438  // id as an int. This should be safe since this is only used with chaps, which
439  // we also control.
440  static PK11SlotInfo* GetTPMSlotForIdOnWorkerThread(SECMODModule* chaps_module,
441                                                     CK_SLOT_ID slot_id) {
442    DCHECK(chaps_module);
443
444    DVLOG(3) << "Poking chaps module.";
445    SECStatus rv = SECMOD_UpdateSlotList(chaps_module);
446    if (rv != SECSuccess)
447      PLOG(ERROR) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
448
449    PK11SlotInfo* slot = SECMOD_LookupSlot(chaps_module->moduleID, slot_id);
450    if (!slot)
451      LOG(ERROR) << "TPM slot " << slot_id << " not found.";
452    return slot;
453  }
454
455  bool InitializeNSSForChromeOSUser(
456      const std::string& email,
457      const std::string& username_hash,
458      const base::FilePath& path) {
459    DCHECK(thread_checker_.CalledOnValidThread());
460    if (chromeos_user_map_.find(username_hash) != chromeos_user_map_.end()) {
461      // This user already exists in our mapping.
462      DVLOG(2) << username_hash << " already initialized.";
463      return false;
464    }
465
466    // If test slot is set, slot getter methods will short circuit
467    // checking |chromeos_user_map_|, so there is nothing left to be
468    // initialized.
469    if (test_slot_)
470      return false;
471
472    DVLOG(2) << "Opening NSS DB " << path.value();
473    std::string db_name = base::StringPrintf(
474        "%s %s", kUserNSSDatabaseName, username_hash.c_str());
475    ScopedPK11Slot public_slot(OpenPersistentNSSDBForPath(db_name, path));
476    chromeos_user_map_[username_hash] =
477        new ChromeOSUserData(public_slot.Pass());
478    return true;
479  }
480
481  bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
482    DCHECK(thread_checker_.CalledOnValidThread());
483    DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
484
485    return !chromeos_user_map_[username_hash]
486                ->private_slot_initialization_started();
487  }
488
489  void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
490    DCHECK(thread_checker_.CalledOnValidThread());
491    DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
492
493    chromeos_user_map_[username_hash]
494        ->set_private_slot_initialization_started();
495  }
496
497  void InitializeTPMForChromeOSUser(const std::string& username_hash,
498                                    CK_SLOT_ID slot_id) {
499    DCHECK(thread_checker_.CalledOnValidThread());
500    DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
501    DCHECK(chromeos_user_map_[username_hash]->
502               private_slot_initialization_started());
503
504    if (!chaps_module_)
505      return;
506
507    // Note that a reference is not taken to chaps_module_. This is safe since
508    // NSSInitSingleton is Leaky, so the reference it holds is never released.
509    scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
510    TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
511    base::WorkerPool::PostTaskAndReply(
512        FROM_HERE,
513        base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
514                   slot_id,
515                   tpm_args_ptr),
516        base::Bind(&NSSInitSingleton::OnInitializedTPMForChromeOSUser,
517                   base::Unretained(this),  // NSSInitSingleton is leaky
518                   username_hash,
519                   base::Passed(&tpm_args)),
520        true /* task_is_slow */
521        );
522  }
523
524  void OnInitializedTPMForChromeOSUser(const std::string& username_hash,
525                                       scoped_ptr<TPMModuleAndSlot> tpm_args) {
526    DCHECK(thread_checker_.CalledOnValidThread());
527    DVLOG(2) << "Got tpm slot for " << username_hash << " "
528             << !!tpm_args->tpm_slot;
529    chromeos_user_map_[username_hash]->SetPrivateSlot(
530        ScopedPK11Slot(tpm_args->tpm_slot));
531  }
532
533  void InitializePrivateSoftwareSlotForChromeOSUser(
534      const std::string& username_hash) {
535    DCHECK(thread_checker_.CalledOnValidThread());
536    VLOG(1) << "using software private slot for " << username_hash;
537    DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
538    DCHECK(chromeos_user_map_[username_hash]->
539               private_slot_initialization_started());
540
541    chromeos_user_map_[username_hash]->SetPrivateSlot(
542        chromeos_user_map_[username_hash]->GetPublicSlot());
543  }
544
545  ScopedPK11Slot GetPublicSlotForChromeOSUser(
546      const std::string& username_hash) {
547    DCHECK(thread_checker_.CalledOnValidThread());
548
549    if (username_hash.empty()) {
550      DVLOG(2) << "empty username_hash";
551      return ScopedPK11Slot();
552    }
553
554    if (test_slot_) {
555      DVLOG(2) << "returning test_slot_ for " << username_hash;
556      return ScopedPK11Slot(PK11_ReferenceSlot(test_slot_));
557    }
558
559    if (chromeos_user_map_.find(username_hash) == chromeos_user_map_.end()) {
560      LOG(ERROR) << username_hash << " not initialized.";
561      return ScopedPK11Slot();
562    }
563    return chromeos_user_map_[username_hash]->GetPublicSlot();
564  }
565
566  ScopedPK11Slot GetPrivateSlotForChromeOSUser(
567      const std::string& username_hash,
568      const base::Callback<void(ScopedPK11Slot)>& callback) {
569    DCHECK(thread_checker_.CalledOnValidThread());
570
571    if (username_hash.empty()) {
572      DVLOG(2) << "empty username_hash";
573      if (!callback.is_null()) {
574        base::MessageLoop::current()->PostTask(
575            FROM_HERE, base::Bind(callback, base::Passed(ScopedPK11Slot())));
576      }
577      return ScopedPK11Slot();
578    }
579
580    DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
581
582    if (test_slot_) {
583      DVLOG(2) << "returning test_slot_ for " << username_hash;
584      return ScopedPK11Slot(PK11_ReferenceSlot(test_slot_));
585    }
586
587    return chromeos_user_map_[username_hash]->GetPrivateSlot(callback);
588  }
589
590  void CloseTestChromeOSUser(const std::string& username_hash) {
591    DCHECK(thread_checker_.CalledOnValidThread());
592    ChromeOSUserMap::iterator i = chromeos_user_map_.find(username_hash);
593    DCHECK(i != chromeos_user_map_.end());
594    delete i->second;
595    chromeos_user_map_.erase(i);
596  }
597#endif  // defined(OS_CHROMEOS)
598
599
600  bool OpenTestNSSDB() {
601    DCHECK(thread_checker_.CalledOnValidThread());
602    // NSS is allowed to do IO on the current thread since dispatching
603    // to a dedicated thread would still have the affect of blocking
604    // the current thread, due to NSS's internal locking requirements
605    base::ThreadRestrictions::ScopedAllowIO allow_io;
606
607    if (test_slot_)
608      return true;
609    if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
610      return false;
611    test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), kTestTPMTokenName);
612    return !!test_slot_;
613  }
614
615  void CloseTestNSSDB() {
616    DCHECK(thread_checker_.CalledOnValidThread());
617    // NSS is allowed to do IO on the current thread since dispatching
618    // to a dedicated thread would still have the affect of blocking
619    // the current thread, due to NSS's internal locking requirements
620    base::ThreadRestrictions::ScopedAllowIO allow_io;
621
622    if (!test_slot_)
623      return;
624    SECStatus status = SECMOD_CloseUserDB(test_slot_);
625    if (status != SECSuccess)
626      PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
627    PK11_FreeSlot(test_slot_);
628    test_slot_ = NULL;
629    ignore_result(g_test_nss_db_dir.Get().Delete());
630  }
631
632  PK11SlotInfo* GetPersistentNSSKeySlot() {
633    // TODO(mattm): Change to DCHECK when callers have been fixed.
634    if (!thread_checker_.CalledOnValidThread()) {
635      DVLOG(1) << "Called on wrong thread.\n"
636               << base::debug::StackTrace().ToString();
637    }
638
639    if (test_slot_)
640      return PK11_ReferenceSlot(test_slot_);
641    return PK11_GetInternalKeySlot();
642  }
643
644#if defined(OS_CHROMEOS)
645  PK11SlotInfo* GetSystemNSSKeySlot() {
646    DCHECK(thread_checker_.CalledOnValidThread());
647
648    if (test_slot_)
649      return PK11_ReferenceSlot(test_slot_);
650
651    // TODO(mattm): chromeos::TPMTokenloader always calls
652    // InitializeTPMTokenAndSystemSlot with slot 0.  If the system slot is
653    // disabled, tpm_slot_ will be the first user's slot instead. Can that be
654    // detected and return NULL instead?
655    if (tpm_token_enabled_for_nss_ && IsTPMTokenReady(base::Closure()))
656      return PK11_ReferenceSlot(tpm_slot_);
657    // If we were supposed to get the hardware token, but were
658    // unable to, return NULL rather than fall back to sofware.
659    return NULL;
660  }
661#endif
662
663#if defined(USE_NSS)
664  base::Lock* write_lock() {
665    return &write_lock_;
666  }
667#endif  // defined(USE_NSS)
668
669  // This method is used to force NSS to be initialized without a DB.
670  // Call this method before NSSInitSingleton() is constructed.
671  static void ForceNoDBInit() {
672    force_nodb_init_ = true;
673  }
674
675 private:
676  friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
677
678  NSSInitSingleton()
679      : tpm_token_enabled_for_nss_(false),
680        initializing_tpm_token_(false),
681        chaps_module_(NULL),
682        test_slot_(NULL),
683        tpm_slot_(NULL),
684        root_(NULL) {
685    base::TimeTicks start_time = base::TimeTicks::Now();
686
687    // It's safe to construct on any thread, since LazyInstance will prevent any
688    // other threads from accessing until the constructor is done.
689    thread_checker_.DetachFromThread();
690
691    DisableAESNIIfNeeded();
692
693    EnsureNSPRInit();
694
695    // We *must* have NSS >= 3.14.3.
696    COMPILE_ASSERT(
697        (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
698        (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
699        (NSS_VMAJOR > 3),
700        nss_version_check_failed);
701    // Also check the run-time NSS version.
702    // NSS_VersionCheck is a >= check, not strict equality.
703    if (!NSS_VersionCheck("3.14.3")) {
704      LOG(FATAL) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
705                    "required. Please upgrade to the latest NSS, and if you "
706                    "still get this error, contact your distribution "
707                    "maintainer.";
708    }
709
710    SECStatus status = SECFailure;
711    bool nodb_init = force_nodb_init_;
712
713#if !defined(USE_NSS)
714    // Use the system certificate store, so initialize NSS without database.
715    nodb_init = true;
716#endif
717
718    if (nodb_init) {
719      status = NSS_NoDB_Init(NULL);
720      if (status != SECSuccess) {
721        CrashOnNSSInitFailure();
722        return;
723      }
724#if defined(OS_IOS)
725      root_ = InitDefaultRootCerts();
726#endif  // defined(OS_IOS)
727    } else {
728#if defined(USE_NSS)
729      base::FilePath database_dir = GetInitialConfigDirectory();
730      if (!database_dir.empty()) {
731        // This duplicates the work which should have been done in
732        // EarlySetupForNSSInit. However, this function is idempotent so
733        // there's no harm done.
734        UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
735
736        // Initialize with a persistent database (likely, ~/.pki/nssdb).
737        // Use "sql:" which can be shared by multiple processes safely.
738        std::string nss_config_dir =
739            base::StringPrintf("sql:%s", database_dir.value().c_str());
740#if defined(OS_CHROMEOS)
741        status = NSS_Init(nss_config_dir.c_str());
742#else
743        status = NSS_InitReadWrite(nss_config_dir.c_str());
744#endif
745        if (status != SECSuccess) {
746          LOG(ERROR) << "Error initializing NSS with a persistent "
747                        "database (" << nss_config_dir
748                     << "): " << GetNSSErrorMessage();
749        }
750      }
751      if (status != SECSuccess) {
752        VLOG(1) << "Initializing NSS without a persistent database.";
753        status = NSS_NoDB_Init(NULL);
754        if (status != SECSuccess) {
755          CrashOnNSSInitFailure();
756          return;
757        }
758      }
759
760      PK11_SetPasswordFunc(PKCS11PasswordFunc);
761
762      // If we haven't initialized the password for the NSS databases,
763      // initialize an empty-string password so that we don't need to
764      // log in.
765      PK11SlotInfo* slot = PK11_GetInternalKeySlot();
766      if (slot) {
767        // PK11_InitPin may write to the keyDB, but no other thread can use NSS
768        // yet, so we don't need to lock.
769        if (PK11_NeedUserInit(slot))
770          PK11_InitPin(slot, NULL, NULL);
771        PK11_FreeSlot(slot);
772      }
773
774      root_ = InitDefaultRootCerts();
775#endif  // defined(USE_NSS)
776    }
777
778    // Disable MD5 certificate signatures. (They are disabled by default in
779    // NSS 3.14.)
780    NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
781    NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
782                           0, NSS_USE_ALG_IN_CERT_SIGNATURE);
783
784    // The UMA bit is conditionally set for this histogram in
785    // chrome/common/startup_metric_utils.cc .
786    HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
787                           base::TimeTicks::Now() - start_time,
788                           base::TimeDelta::FromMilliseconds(10),
789                           base::TimeDelta::FromHours(1),
790                           50);
791  }
792
793  // NOTE(willchan): We don't actually execute this code since we leak NSS to
794  // prevent non-joinable threads from using NSS after it's already been shut
795  // down.
796  ~NSSInitSingleton() {
797#if defined(OS_CHROMEOS)
798    STLDeleteValues(&chromeos_user_map_);
799#endif
800    if (tpm_slot_) {
801      PK11_FreeSlot(tpm_slot_);
802      tpm_slot_ = NULL;
803    }
804    CloseTestNSSDB();
805    if (root_) {
806      SECMOD_UnloadUserModule(root_);
807      SECMOD_DestroyModule(root_);
808      root_ = NULL;
809    }
810    if (chaps_module_) {
811      SECMOD_UnloadUserModule(chaps_module_);
812      SECMOD_DestroyModule(chaps_module_);
813      chaps_module_ = NULL;
814    }
815
816    SECStatus status = NSS_Shutdown();
817    if (status != SECSuccess) {
818      // We VLOG(1) because this failure is relatively harmless (leaking, but
819      // we're shutting down anyway).
820      VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
821    }
822  }
823
824#if defined(USE_NSS) || defined(OS_IOS)
825  // Load nss's built-in root certs.
826  SECMODModule* InitDefaultRootCerts() {
827    SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
828    if (root)
829      return root;
830
831    // Aw, snap.  Can't find/load root cert shared library.
832    // This will make it hard to talk to anybody via https.
833    // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
834    return NULL;
835  }
836
837  // Load the given module for this NSS session.
838  static SECMODModule* LoadModule(const char* name,
839                                  const char* library_path,
840                                  const char* params) {
841    std::string modparams = base::StringPrintf(
842        "name=\"%s\" library=\"%s\" %s",
843        name, library_path, params ? params : "");
844
845    // Shouldn't need to const_cast here, but SECMOD doesn't properly
846    // declare input string arguments as const.  Bug
847    // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
848    // on NSS codebase to address this.
849    SECMODModule* module = SECMOD_LoadUserModule(
850        const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
851    if (!module) {
852      LOG(ERROR) << "Error loading " << name << " module into NSS: "
853                 << GetNSSErrorMessage();
854      return NULL;
855    }
856    if (!module->loaded) {
857      LOG(ERROR) << "After loading " << name << ", loaded==false: "
858                 << GetNSSErrorMessage();
859      SECMOD_DestroyModule(module);
860      return NULL;
861    }
862    return module;
863  }
864#endif
865
866  static PK11SlotInfo* OpenUserDB(const base::FilePath& path,
867                                  const std::string& description) {
868    const std::string modspec =
869        base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
870                           path.value().c_str(),
871                           description.c_str());
872    PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
873    if (db_slot) {
874      if (PK11_NeedUserInit(db_slot))
875        PK11_InitPin(db_slot, NULL, NULL);
876    }
877    else {
878      LOG(ERROR) << "Error opening persistent database (" << modspec
879                 << "): " << GetNSSErrorMessage();
880    }
881    return db_slot;
882  }
883
884  static void DisableAESNIIfNeeded() {
885    if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
886      // Some versions of NSS have a bug that causes AVX instructions to be
887      // used without testing whether XSAVE is enabled by the operating system.
888      // In order to work around this, we disable AES-NI in NSS when we find
889      // that |has_avx()| is false (which includes the XSAVE test). See
890      // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
891      base::CPU cpu;
892
893      if (cpu.has_avx_hardware() && !cpu.has_avx()) {
894        base::Environment::Create()->SetVar("NSS_DISABLE_HW_AES", "1");
895      }
896    }
897  }
898
899  // If this is set to true NSS is forced to be initialized without a DB.
900  static bool force_nodb_init_;
901
902  bool tpm_token_enabled_for_nss_;
903  bool initializing_tpm_token_;
904  typedef std::vector<base::Closure> TPMReadyCallbackList;
905  TPMReadyCallbackList tpm_ready_callback_list_;
906  SECMODModule* chaps_module_;
907  PK11SlotInfo* test_slot_;
908  PK11SlotInfo* tpm_slot_;
909  SECMODModule* root_;
910#if defined(OS_CHROMEOS)
911  typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
912  ChromeOSUserMap chromeos_user_map_;
913#endif
914#if defined(USE_NSS)
915  // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
916  // is fixed, we will no longer need the lock.
917  base::Lock write_lock_;
918#endif  // defined(USE_NSS)
919
920  base::ThreadChecker thread_checker_;
921};
922
923// static
924bool NSSInitSingleton::force_nodb_init_ = false;
925
926base::LazyInstance<NSSInitSingleton>::Leaky
927    g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
928}  // namespace
929
930const char kTestTPMTokenName[] = "Test DB";
931
932#if defined(USE_NSS)
933void EarlySetupForNSSInit() {
934  base::FilePath database_dir = GetInitialConfigDirectory();
935  if (!database_dir.empty())
936    UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
937}
938#endif
939
940void EnsureNSPRInit() {
941  g_nspr_singleton.Get();
942}
943
944void InitNSSSafely() {
945  // We might fork, but we haven't loaded any security modules.
946  DisableNSSForkCheck();
947  // If we're sandboxed, we shouldn't be able to open user security modules,
948  // but it's more correct to tell NSS to not even try.
949  // Loading user security modules would have security implications.
950  ForceNSSNoDBInit();
951  // Initialize NSS.
952  EnsureNSSInit();
953}
954
955void EnsureNSSInit() {
956  // Initializing SSL causes us to do blocking IO.
957  // Temporarily allow it until we fix
958  //   http://code.google.com/p/chromium/issues/detail?id=59847
959  base::ThreadRestrictions::ScopedAllowIO allow_io;
960  g_nss_singleton.Get();
961}
962
963void ForceNSSNoDBInit() {
964  NSSInitSingleton::ForceNoDBInit();
965}
966
967void DisableNSSForkCheck() {
968  scoped_ptr<base::Environment> env(base::Environment::Create());
969  env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
970}
971
972void LoadNSSLibraries() {
973  // Some NSS libraries are linked dynamically so load them here.
974#if defined(USE_NSS)
975  // Try to search for multiple directories to load the libraries.
976  std::vector<base::FilePath> paths;
977
978  // Use relative path to Search PATH for the library files.
979  paths.push_back(base::FilePath());
980
981  // For Debian derivatives NSS libraries are located here.
982  paths.push_back(base::FilePath("/usr/lib/nss"));
983
984  // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
985#if defined(ARCH_CPU_X86_64)
986  paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
987#elif defined(ARCH_CPU_X86)
988  paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
989#elif defined(ARCH_CPU_ARMEL)
990#if defined(__ARM_PCS_VFP)
991  paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
992#else
993  paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
994#endif  // defined(__ARM_PCS_VFP)
995#elif defined(ARCH_CPU_MIPSEL)
996  paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
997#endif  // defined(ARCH_CPU_X86_64)
998
999  // A list of library files to load.
1000  std::vector<std::string> libs;
1001  libs.push_back("libsoftokn3.so");
1002  libs.push_back("libfreebl3.so");
1003
1004  // For each combination of library file and path, check for existence and
1005  // then load.
1006  size_t loaded = 0;
1007  for (size_t i = 0; i < libs.size(); ++i) {
1008    for (size_t j = 0; j < paths.size(); ++j) {
1009      base::FilePath path = paths[j].Append(libs[i]);
1010      base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
1011      if (lib) {
1012        ++loaded;
1013        break;
1014      }
1015    }
1016  }
1017
1018  if (loaded == libs.size()) {
1019    VLOG(3) << "NSS libraries loaded.";
1020  } else {
1021    LOG(ERROR) << "Failed to load NSS libraries.";
1022  }
1023#endif  // defined(USE_NSS)
1024}
1025
1026bool CheckNSSVersion(const char* version) {
1027  return !!NSS_VersionCheck(version);
1028}
1029
1030#if defined(USE_NSS)
1031ScopedTestNSSDB::ScopedTestNSSDB()
1032  : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
1033}
1034
1035ScopedTestNSSDB::~ScopedTestNSSDB() {
1036  // Don't close when NSS is < 3.15.1, because it would require an additional
1037  // sleep for 1 second after closing the database, due to
1038  // http://bugzil.la/875601.
1039  if (NSS_VersionCheck("3.15.1")) {
1040    g_nss_singleton.Get().CloseTestNSSDB();
1041  }
1042}
1043
1044base::Lock* GetNSSWriteLock() {
1045  return g_nss_singleton.Get().write_lock();
1046}
1047
1048AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
1049  // May be NULL if the lock is not needed in our version of NSS.
1050  if (lock_)
1051    lock_->Acquire();
1052}
1053
1054AutoNSSWriteLock::~AutoNSSWriteLock() {
1055  if (lock_) {
1056    lock_->AssertAcquired();
1057    lock_->Release();
1058  }
1059}
1060
1061AutoSECMODListReadLock::AutoSECMODListReadLock()
1062      : lock_(SECMOD_GetDefaultModuleListLock()) {
1063    SECMOD_GetReadLock(lock_);
1064  }
1065
1066AutoSECMODListReadLock::~AutoSECMODListReadLock() {
1067  SECMOD_ReleaseReadLock(lock_);
1068}
1069
1070#endif  // defined(USE_NSS)
1071
1072#if defined(OS_CHROMEOS)
1073PK11SlotInfo* GetSystemNSSKeySlot() {
1074  return g_nss_singleton.Get().GetSystemNSSKeySlot();
1075}
1076
1077void EnableTPMTokenForNSS() {
1078  g_nss_singleton.Get().EnableTPMTokenForNSS();
1079}
1080
1081bool IsTPMTokenEnabledForNSS() {
1082  return g_nss_singleton.Get().IsTPMTokenEnabledForNSS();
1083}
1084
1085bool IsTPMTokenReady(const base::Closure& callback) {
1086  return g_nss_singleton.Get().IsTPMTokenReady(callback);
1087}
1088
1089void InitializeTPMTokenAndSystemSlot(
1090    int token_slot_id,
1091    const base::Callback<void(bool)>& callback) {
1092  g_nss_singleton.Get().InitializeTPMTokenAndSystemSlot(token_slot_id,
1093                                                        callback);
1094}
1095
1096ScopedTestNSSChromeOSUser::ScopedTestNSSChromeOSUser(
1097    const std::string& username_hash)
1098    : username_hash_(username_hash), constructed_successfully_(false) {
1099  if (!temp_dir_.CreateUniqueTempDir())
1100    return;
1101  constructed_successfully_ =
1102      InitializeNSSForChromeOSUser(username_hash,
1103                                   username_hash,
1104                                   temp_dir_.path());
1105}
1106
1107ScopedTestNSSChromeOSUser::~ScopedTestNSSChromeOSUser() {
1108  if (constructed_successfully_)
1109    g_nss_singleton.Get().CloseTestChromeOSUser(username_hash_);
1110}
1111
1112void ScopedTestNSSChromeOSUser::FinishInit() {
1113  DCHECK(constructed_successfully_);
1114  if (!ShouldInitializeTPMForChromeOSUser(username_hash_))
1115    return;
1116  WillInitializeTPMForChromeOSUser(username_hash_);
1117  InitializePrivateSoftwareSlotForChromeOSUser(username_hash_);
1118}
1119
1120bool InitializeNSSForChromeOSUser(
1121    const std::string& email,
1122    const std::string& username_hash,
1123    const base::FilePath& path) {
1124  return g_nss_singleton.Get().InitializeNSSForChromeOSUser(
1125      email, username_hash, path);
1126}
1127
1128bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
1129  return g_nss_singleton.Get().ShouldInitializeTPMForChromeOSUser(
1130      username_hash);
1131}
1132
1133void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
1134  g_nss_singleton.Get().WillInitializeTPMForChromeOSUser(username_hash);
1135}
1136
1137void InitializeTPMForChromeOSUser(
1138    const std::string& username_hash,
1139    CK_SLOT_ID slot_id) {
1140  g_nss_singleton.Get().InitializeTPMForChromeOSUser(username_hash, slot_id);
1141}
1142void InitializePrivateSoftwareSlotForChromeOSUser(
1143    const std::string& username_hash) {
1144  g_nss_singleton.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1145      username_hash);
1146}
1147ScopedPK11Slot GetPublicSlotForChromeOSUser(const std::string& username_hash) {
1148  return g_nss_singleton.Get().GetPublicSlotForChromeOSUser(username_hash);
1149}
1150ScopedPK11Slot GetPrivateSlotForChromeOSUser(
1151    const std::string& username_hash,
1152    const base::Callback<void(ScopedPK11Slot)>& callback) {
1153  return g_nss_singleton.Get().GetPrivateSlotForChromeOSUser(username_hash,
1154                                                             callback);
1155}
1156#endif  // defined(OS_CHROMEOS)
1157
1158base::Time PRTimeToBaseTime(PRTime prtime) {
1159  return base::Time::FromInternalValue(
1160      prtime + base::Time::UnixEpoch().ToInternalValue());
1161}
1162
1163PRTime BaseTimeToPRTime(base::Time time) {
1164  return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1165}
1166
1167PK11SlotInfo* GetPersistentNSSKeySlot() {
1168  return g_nss_singleton.Get().GetPersistentNSSKeySlot();
1169}
1170
1171}  // namespace crypto
1172