[M120 Migration][VD] Enable direct rendering for TVPlus
[platform/framework/web/chromium-efl.git] / crypto / nss_util.cc
1 // Copyright 2012 The Chromium Authors
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
7 #include <nss.h>
8 #include <pk11pub.h>
9 #include <plarena.h>
10 #include <prerror.h>
11 #include <prinit.h>
12 #include <prtime.h>
13 #include <secmod.h>
14
15 #include <memory>
16 #include <utility>
17
18 #include "base/base_paths.h"
19 #include "base/containers/flat_map.h"
20 #include "base/debug/alias.h"
21 #include "base/files/file_path.h"
22 #include "base/files/file_util.h"
23 #include "base/lazy_instance.h"
24 #include "base/logging.h"
25 #include "base/path_service.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/threading/scoped_blocking_call.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "build/build_config.h"
30 #include "build/chromeos_buildflags.h"
31 #include "crypto/nss_crypto_module_delegate.h"
32 #include "crypto/nss_util_internal.h"
33
34 namespace crypto {
35
36 namespace {
37
38 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
39
40 // Fake certificate authority database used for testing.
41 static const base::FilePath::CharType kReadOnlyCertDB[] =
42     FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
43
44 #else
45
46 base::FilePath GetDefaultConfigDirectory() {
47   base::FilePath dir;
48   base::PathService::Get(base::DIR_HOME, &dir);
49   if (dir.empty()) {
50     LOG(ERROR) << "Failed to get home directory.";
51     return dir;
52   }
53   dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
54   if (!base::CreateDirectory(dir)) {
55     LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
56     dir.clear();
57   }
58   DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
59   return dir;
60 }
61
62 #endif  // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
63
64 // On non-Chrome OS platforms, return the default config directory. On Chrome OS
65 // test images, return a read-only directory with fake root CA certs (which are
66 // used by the local Google Accounts server mock we use when testing our login
67 // code). On Chrome OS non-test images (where the read-only directory doesn't
68 // exist), return an empty path.
69 base::FilePath GetInitialConfigDirectory() {
70 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
71   base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
72   if (!base::PathExists(database_dir))
73     database_dir.clear();
74   return database_dir;
75 #else
76   return GetDefaultConfigDirectory();
77 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
78 }
79
80 // This callback for NSS forwards all requests to a caller-specified
81 // CryptoModuleBlockingPasswordDelegate object.
82 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
83   crypto::CryptoModuleBlockingPasswordDelegate* delegate =
84       reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
85   if (delegate) {
86     bool cancelled = false;
87     std::string password = delegate->RequestPassword(
88         PK11_GetTokenName(slot), retry != PR_FALSE, &cancelled);
89     if (cancelled)
90       return nullptr;
91     char* result = PORT_Strdup(password.c_str());
92     password.replace(0, password.size(), password.size(), 0);
93     return result;
94   }
95   DLOG(ERROR) << "PK11 password requested with nullptr arg";
96   return nullptr;
97 }
98
99 // A singleton to initialize/deinitialize NSPR.
100 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
101 // Now that we're leaking the singleton, we could merge back with the NSS
102 // singleton.
103 class NSPRInitSingleton {
104  private:
105   friend struct base::LazyInstanceTraitsBase<NSPRInitSingleton>;
106
107   NSPRInitSingleton() { PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); }
108
109   // NOTE(willchan): We don't actually cleanup on destruction since we leak NSS
110   // to prevent non-joinable threads from using NSS after it's already been
111   // shut down.
112   ~NSPRInitSingleton() = delete;
113 };
114
115 base::LazyInstance<NSPRInitSingleton>::Leaky g_nspr_singleton =
116     LAZY_INSTANCE_INITIALIZER;
117
118 // Force a crash with error info on NSS_NoDB_Init failure.
119 void CrashOnNSSInitFailure() {
120   int nss_error = PR_GetError();
121   int os_error = PR_GetOSError();
122   base::debug::Alias(&nss_error);
123   base::debug::Alias(&os_error);
124   LOG(ERROR) << "Error initializing NSS without a persistent database: "
125              << GetNSSErrorMessage();
126   LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
127 }
128
129 class NSSInitSingleton {
130  public:
131   // NOTE(willchan): We don't actually cleanup on destruction since we leak NSS
132   // to prevent non-joinable threads from using NSS after it's already been
133   // shut down.
134   ~NSSInitSingleton() = delete;
135
136   ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
137                                    const std::string& description) {
138     base::AutoLock lock(slot_map_lock_);
139
140     auto slot_map_iter = slot_map_.find(path);
141     if (slot_map_iter != slot_map_.end()) {
142       // PK11_ReferenceSlot returns a new PK11Slot instance which refers
143       // to the same slot.
144       return ScopedPK11Slot(PK11_ReferenceSlot(slot_map_iter->second.get()));
145     }
146
147     const std::string modspec =
148         base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
149                            path.value().c_str(), description.c_str());
150
151     // TODO(crbug.com/1163303): Presumably there's a race condition with
152     // session_manager around creating/opening the software NSS database. The
153     // retry loop is a temporary workaround that should at least reduce the
154     // amount of failures until a proper fix is implemented.
155     PK11SlotInfo* db_slot_info = nullptr;
156     int attempts_counter = 0;
157     for (; !db_slot_info && (attempts_counter < 10); ++attempts_counter) {
158       db_slot_info = SECMOD_OpenUserDB(modspec.c_str());
159     }
160     if (db_slot_info && (attempts_counter > 1)) {
161       LOG(ERROR) << "Opening persistent database failed "
162                  << attempts_counter - 1 << " times before succeeding";
163     }
164
165     if (db_slot_info) {
166       if (PK11_NeedUserInit(db_slot_info))
167         PK11_InitPin(db_slot_info, nullptr, nullptr);
168       slot_map_[path] = ScopedPK11Slot(PK11_ReferenceSlot(db_slot_info));
169     } else {
170       LOG(ERROR) << "Error opening persistent database (" << modspec
171                  << "): " << GetNSSErrorMessage();
172 #if BUILDFLAG(IS_CHROMEOS_ASH)
173       DiagnosePublicSlotAndCrash(path);
174 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
175     }
176
177     return ScopedPK11Slot(db_slot_info);
178   }
179
180   SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
181     if (!slot) {
182       return SECFailure;
183     }
184
185     base::AutoLock lock(slot_map_lock_);
186     CK_SLOT_ID slot_id = PK11_GetSlotID(slot);
187     for (auto const& [stored_path, stored_slot] : slot_map_) {
188       if (PK11_GetSlotID(stored_slot.get()) == slot_id) {
189         slot_map_.erase(stored_path);
190         return SECMOD_CloseUserDB(slot);
191       }
192     }
193     return SECFailure;
194   }
195
196  private:
197   friend struct base::LazyInstanceTraitsBase<NSSInitSingleton>;
198
199   NSSInitSingleton() {
200     // Initializing NSS causes us to do blocking IO.
201     // Temporarily allow it until we fix
202     //   http://code.google.com/p/chromium/issues/detail?id=59847
203     ScopedAllowBlockingForNSS allow_blocking;
204
205     EnsureNSPRInit();
206 #if BUILDFLAG(IS_TIZEN)
207     LOG(INFO) << " Tizen 8.0 platform NSS library version is 3.34 and open "
208                  "source expects 3.35 or higher";
209 #else
210     // We *must* have NSS >= 3.35 at compile time.
211     static_assert((NSS_VMAJOR == 3 && NSS_VMINOR >= 35) || (NSS_VMAJOR > 3),
212                   "nss version check failed");
213     // Also check the run-time NSS version.
214     // NSS_VersionCheck is a >= check, not strict equality.
215     if (!NSS_VersionCheck("3.35")) {
216       LOG(FATAL) << "NSS_VersionCheck(\"3.35\") failed. NSS >= 3.35 is "
217                     "required. Please upgrade to the latest NSS, and if you "
218                     "still get this error, contact your distribution "
219                     "maintainer.";
220     }
221 #endif
222
223     SECStatus status = SECFailure;
224     base::FilePath database_dir = GetInitialConfigDirectory();
225     // In MSAN, all loaded libraries needs to be instrumented. But the user
226     // config may reference an uninstrumented module, so load NSS without cert
227     // DBs instead. Tests should ideally be run under
228     // testing/run_with_dummy_home.py to eliminate dependencies on user
229     // configuration, but the bots are not currently configured to do so. This
230     // workaround may be removed if/when the bots use run_with_dummy_home.py.
231 #if !defined(MEMORY_SANITIZER)
232     if (!database_dir.empty()) {
233       // Initialize with a persistent database (likely, ~/.pki/nssdb).
234       // Use "sql:" which can be shared by multiple processes safely.
235       std::string nss_config_dir =
236           base::StringPrintf("sql:%s", database_dir.value().c_str());
237 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
238       status = NSS_Init(nss_config_dir.c_str());
239 #else
240       status = NSS_InitReadWrite(nss_config_dir.c_str());
241 #endif
242       if (status != SECSuccess) {
243         LOG(ERROR) << "Error initializing NSS with a persistent "
244                       "database ("
245                    << nss_config_dir << "): " << GetNSSErrorMessage();
246       }
247     }
248 #endif  // !defined(MEMORY_SANITIZER)
249     if (status != SECSuccess) {
250       VLOG(1) << "Initializing NSS without a persistent database.";
251       status = NSS_NoDB_Init(nullptr);
252       if (status != SECSuccess) {
253         CrashOnNSSInitFailure();
254         return;
255       }
256     }
257
258     PK11_SetPasswordFunc(PKCS11PasswordFunc);
259
260     // If we haven't initialized the password for the NSS databases,
261     // initialize an empty-string password so that we don't need to
262     // log in.
263     PK11SlotInfo* slot = PK11_GetInternalKeySlot();
264     if (slot) {
265       // PK11_InitPin may write to the keyDB, but no other thread can use NSS
266       // yet, so we don't need to lock.
267       if (PK11_NeedUserInit(slot))
268         PK11_InitPin(slot, nullptr, nullptr);
269       PK11_FreeSlot(slot);
270     }
271
272     // Load nss's built-in root certs.
273     //
274     // TODO(mattm): DCHECK this succeeded when crbug.com/310972 is fixed.
275     // Failing to load root certs will it hard to talk to anybody via https.
276     LoadNSSModule("Root Certs", "libnssckbi.so", nullptr);
277
278     // Disable MD5 certificate signatures. (They are disabled by default in
279     // NSS 3.14.)
280     NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
281     NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, 0,
282                            NSS_USE_ALG_IN_CERT_SIGNATURE);
283   }
284
285   // Stores opened software NSS databases.
286   base::flat_map<base::FilePath, /*slot=*/ScopedPK11Slot> slot_map_
287       GUARDED_BY(slot_map_lock_);
288   // Ensures thread-safety for the methods that modify slot_map_.
289   // Performance considerations:
290   // Opening/closing a database is a rare operation in Chrome. Actually opening
291   // a database is a blocking I/O operation. Chrome doesn't open a lot of
292   // different databases in parallel. So, waiting for another thread to finish
293   // opening a database and (almost certainly) reusing the result is comparable
294   // to opening the same database twice in parallel (but the latter is not
295   // supported by NSS).
296   base::Lock slot_map_lock_;
297 };
298
299 base::LazyInstance<NSSInitSingleton>::Leaky g_nss_singleton =
300     LAZY_INSTANCE_INITIALIZER;
301 }  // namespace
302
303 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
304                                  const std::string& description) {
305   return g_nss_singleton.Get().OpenSoftwareNSSDB(path, description);
306 }
307
308 SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
309   return g_nss_singleton.Get().CloseSoftwareNSSDB(slot);
310 }
311
312 void EnsureNSPRInit() {
313   g_nspr_singleton.Get();
314 }
315
316 void EnsureNSSInit() {
317   g_nss_singleton.Get();
318 }
319
320 bool CheckNSSVersion(const char* version) {
321   return !!NSS_VersionCheck(version);
322 }
323
324 AutoSECMODListReadLock::AutoSECMODListReadLock()
325     : lock_(SECMOD_GetDefaultModuleListLock()) {
326   SECMOD_GetReadLock(lock_);
327 }
328
329 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
330   SECMOD_ReleaseReadLock(lock_);
331 }
332
333 base::Time PRTimeToBaseTime(PRTime prtime) {
334   return base::Time::FromInternalValue(
335       prtime + base::Time::UnixEpoch().ToInternalValue());
336 }
337
338 PRTime BaseTimeToPRTime(base::Time time) {
339   return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
340 }
341
342 SECMODModule* LoadNSSModule(const char* name,
343                             const char* library_path,
344                             const char* params) {
345   std::string modparams =
346       base::StringPrintf("name=\"%s\" library=\"%s\" %s", name, library_path,
347                          params ? params : "");
348
349   // Shouldn't need to const_cast here, but SECMOD doesn't properly declare
350   // input string arguments as const.  Bug
351   // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed on NSS
352   // codebase to address this.
353   SECMODModule* module = SECMOD_LoadUserModule(
354       const_cast<char*>(modparams.c_str()), nullptr, PR_FALSE);
355   if (!module) {
356     LOG(ERROR) << "Error loading " << name
357                << " module into NSS: " << GetNSSErrorMessage();
358     return nullptr;
359   }
360   if (!module->loaded) {
361     LOG(ERROR) << "After loading " << name
362                << ", loaded==false: " << GetNSSErrorMessage();
363     SECMOD_DestroyModule(module);
364     return nullptr;
365   }
366   return module;
367 }
368
369 std::string GetNSSErrorMessage() {
370   std::string result;
371   if (PR_GetErrorTextLength()) {
372     std::unique_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
373     PRInt32 copied = PR_GetErrorText(error_text.get());
374     result = std::string(error_text.get(), copied);
375   } else {
376     result = base::StringPrintf("NSS error code: %d", PR_GetError());
377   }
378   return result;
379 }
380
381 }  // namespace crypto