1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 /*
5  * The following handles the loading, unloading and management of
6  * various PCKS #11 modules
7  */
8 #define FORCE_PR_LOG 1
9 #include "seccomon.h"
10 #include "pkcs11.h"
11 #include "secmod.h"
12 #include "prlink.h"
13 #include "pk11func.h"
14 #include "secmodi.h"
15 #include "secmodti.h"
16 #include "nssilock.h"
17 #include "secerr.h"
18 #include "prenv.h"
19 #include "utilparst.h"
20 #include "prio.h"
21 #include "prprf.h"
22 #include <stdio.h>
23 #include "prsystem.h"
24 
25 #define DEBUG_MODULE 1
26 
27 #ifdef DEBUG_MODULE
28 static char *modToDBG = NULL;
29 
30 #include "debug_module.c"
31 #endif
32 
33 /* build the PKCS #11 2.01 lock files */
34 CK_RV PR_CALLBACK
secmodCreateMutext(CK_VOID_PTR_PTR pmutex)35 secmodCreateMutext(CK_VOID_PTR_PTR pmutex)
36 {
37     *pmutex = (CK_VOID_PTR)PZ_NewLock(nssILockOther);
38     if (*pmutex)
39         return CKR_OK;
40     return CKR_HOST_MEMORY;
41 }
42 
43 CK_RV PR_CALLBACK
secmodDestroyMutext(CK_VOID_PTR mutext)44 secmodDestroyMutext(CK_VOID_PTR mutext)
45 {
46     PZ_DestroyLock((PZLock *)mutext);
47     return CKR_OK;
48 }
49 
50 CK_RV PR_CALLBACK
secmodLockMutext(CK_VOID_PTR mutext)51 secmodLockMutext(CK_VOID_PTR mutext)
52 {
53     PZ_Lock((PZLock *)mutext);
54     return CKR_OK;
55 }
56 
57 CK_RV PR_CALLBACK
secmodUnlockMutext(CK_VOID_PTR mutext)58 secmodUnlockMutext(CK_VOID_PTR mutext)
59 {
60     PZ_Unlock((PZLock *)mutext);
61     return CKR_OK;
62 }
63 
64 static SECMODModuleID nextModuleID = 1;
65 static const CK_C_INITIALIZE_ARGS secmodLockFunctions = {
66     secmodCreateMutext, secmodDestroyMutext, secmodLockMutext,
67     secmodUnlockMutext, CKF_LIBRARY_CANT_CREATE_OS_THREADS | CKF_OS_LOCKING_OK,
68     NULL
69 };
70 static const CK_C_INITIALIZE_ARGS secmodNoLockArgs = {
71     NULL, NULL, NULL, NULL,
72     CKF_LIBRARY_CANT_CREATE_OS_THREADS, NULL
73 };
74 
75 static PRBool loadSingleThreadedModules = PR_TRUE;
76 static PRBool enforceAlreadyInitializedError = PR_TRUE;
77 static PRBool finalizeModules = PR_TRUE;
78 
79 /* set global options for NSS PKCS#11 module loader */
80 SECStatus
pk11_setGlobalOptions(PRBool noSingleThreadedModules,PRBool allowAlreadyInitializedModules,PRBool dontFinalizeModules)81 pk11_setGlobalOptions(PRBool noSingleThreadedModules,
82                       PRBool allowAlreadyInitializedModules,
83                       PRBool dontFinalizeModules)
84 {
85     if (noSingleThreadedModules) {
86         loadSingleThreadedModules = PR_FALSE;
87     } else {
88         loadSingleThreadedModules = PR_TRUE;
89     }
90     if (allowAlreadyInitializedModules) {
91         enforceAlreadyInitializedError = PR_FALSE;
92     } else {
93         enforceAlreadyInitializedError = PR_TRUE;
94     }
95     if (dontFinalizeModules) {
96         finalizeModules = PR_FALSE;
97     } else {
98         finalizeModules = PR_TRUE;
99     }
100     return SECSuccess;
101 }
102 
103 PRBool
pk11_getFinalizeModulesOption(void)104 pk11_getFinalizeModulesOption(void)
105 {
106     return finalizeModules;
107 }
108 
109 /*
110  * Allow specification loading the same module more than once at init time.
111  * This enables 2 things.
112  *
113  *    1) we can load additional databases by manipulating secmod.db/pkcs11.txt.
114  *    2) we can handle the case where some library has already initialized NSS
115  *    before the main application.
116  *
117  * oldModule is the module we have already initialized.
118  * char *modulespec is the full module spec for the library we want to
119  * initialize.
120  */
121 static SECStatus
secmod_handleReload(SECMODModule * oldModule,SECMODModule * newModule)122 secmod_handleReload(SECMODModule *oldModule, SECMODModule *newModule)
123 {
124     PK11SlotInfo *slot;
125     char *modulespec;
126     char *newModuleSpec;
127     char **children;
128     CK_SLOT_ID *ids;
129     SECMODConfigList *conflist = NULL;
130     SECStatus rv = SECFailure;
131     int count = 0;
132 
133     /* first look for tokens= key words from the module spec */
134     modulespec = newModule->libraryParams;
135     newModuleSpec = secmod_ParseModuleSpecForTokens(PR_TRUE,
136                                                     newModule->isFIPS, modulespec, &children, &ids);
137     if (!newModuleSpec) {
138         return SECFailure;
139     }
140 
141     /*
142      * We are now trying to open a new slot on an already loaded module.
143      * If that slot represents a cert/key database, we don't want to open
144      * multiple copies of that same database. Unfortunately we understand
145      * the softoken flags well enough to be able to do this, so we can only get
146      * the list of already loaded databases if we are trying to open another
147      * internal module.
148      */
149     if (oldModule->internal) {
150         conflist = secmod_GetConfigList(oldModule->isFIPS,
151                                         oldModule->libraryParams, &count);
152     }
153 
154     /* don't open multiple of the same db */
155     if (conflist && secmod_MatchConfigList(newModuleSpec, conflist, count)) {
156         rv = SECSuccess;
157         goto loser;
158     }
159     slot = SECMOD_OpenNewSlot(oldModule, newModuleSpec);
160     if (slot) {
161         int newID;
162         char **thisChild;
163         CK_SLOT_ID *thisID;
164         char *oldModuleSpec;
165 
166         if (secmod_IsInternalKeySlot(newModule)) {
167             pk11_SetInternalKeySlotIfFirst(slot);
168         }
169         newID = slot->slotID;
170         PK11_FreeSlot(slot);
171         for (thisChild = children, thisID = ids; thisChild && *thisChild;
172              thisChild++, thisID++) {
173             if (conflist &&
174                 secmod_MatchConfigList(*thisChild, conflist, count)) {
175                 *thisID = (CK_SLOT_ID)-1;
176                 continue;
177             }
178             slot = SECMOD_OpenNewSlot(oldModule, *thisChild);
179             if (slot) {
180                 *thisID = slot->slotID;
181                 PK11_FreeSlot(slot);
182             } else {
183                 *thisID = (CK_SLOT_ID)-1;
184             }
185         }
186 
187         /* update the old module initialization string in case we need to
188          * shutdown and reinit the whole mess (this is rare, but can happen
189          * when trying to stop smart card insertion/removal threads)... */
190         oldModuleSpec = secmod_MkAppendTokensList(oldModule->arena,
191                                                   oldModule->libraryParams, newModuleSpec, newID,
192                                                   children, ids);
193         if (oldModuleSpec) {
194             oldModule->libraryParams = oldModuleSpec;
195         }
196 
197         rv = SECSuccess;
198     }
199 
200 loser:
201     secmod_FreeChildren(children, ids);
202     PORT_Free(newModuleSpec);
203     if (conflist) {
204         secmod_FreeConfigList(conflist, count);
205     }
206     return rv;
207 }
208 
209 /*
210  * collect the steps we need to initialize a module in a single function
211  */
212 SECStatus
secmod_ModuleInit(SECMODModule * mod,SECMODModule ** reload,PRBool * alreadyLoaded)213 secmod_ModuleInit(SECMODModule *mod, SECMODModule **reload,
214                   PRBool *alreadyLoaded)
215 {
216     CK_C_INITIALIZE_ARGS moduleArgs;
217     CK_VOID_PTR pInitArgs;
218     CK_RV crv;
219 
220     if (reload) {
221         *reload = NULL;
222     }
223 
224     if (!mod || !alreadyLoaded) {
225         PORT_SetError(SEC_ERROR_INVALID_ARGS);
226         return SECFailure;
227     }
228 
229     if (mod->libraryParams == NULL) {
230         if (mod->isThreadSafe) {
231             pInitArgs = (void *)&secmodLockFunctions;
232         } else {
233             pInitArgs = NULL;
234         }
235     } else {
236         if (mod->isThreadSafe) {
237             moduleArgs = secmodLockFunctions;
238         } else {
239             moduleArgs = secmodNoLockArgs;
240         }
241         moduleArgs.LibraryParameters = (void *)mod->libraryParams;
242         pInitArgs = &moduleArgs;
243     }
244     crv = PK11_GETTAB(mod)->C_Initialize(pInitArgs);
245     if (CKR_CRYPTOKI_ALREADY_INITIALIZED == crv) {
246         SECMODModule *oldModule = NULL;
247 
248         /* Library has already been loaded once, if caller expects it, and it
249          * has additional configuration, try reloading it as well. */
250         if (reload != NULL && mod->libraryParams) {
251             oldModule = secmod_FindModuleByFuncPtr(mod->functionList);
252         }
253         /* Library has been loaded by NSS. It means it may be capable of
254          * reloading */
255         if (oldModule) {
256             SECStatus rv;
257             rv = secmod_handleReload(oldModule, mod);
258             if (rv == SECSuccess) {
259                 /* This module should go away soon, since we've
260                  * simply expanded the slots on the old module.
261                  * When it goes away, it should not Finalize since
262                  * that will close our old module as well. Setting
263                  * the function list to NULL will prevent that close */
264                 mod->functionList = NULL;
265                 *reload = oldModule;
266                 return SECSuccess;
267             }
268             SECMOD_DestroyModule(oldModule);
269         }
270         /* reload not possible, fall back to old semantics */
271         if (!enforceAlreadyInitializedError) {
272             *alreadyLoaded = PR_TRUE;
273             return SECSuccess;
274         }
275     }
276     if (crv != CKR_OK) {
277         if (!mod->isThreadSafe ||
278             crv == CKR_NETSCAPE_CERTDB_FAILED ||
279             crv == CKR_NETSCAPE_KEYDB_FAILED) {
280             PORT_SetError(PK11_MapError(crv));
281             return SECFailure;
282         }
283         /* If we had attempted to init a single threaded module "with"
284          * parameters and it failed, should we retry "without" parameters?
285          * (currently we don't retry in this scenario) */
286 
287         if (!loadSingleThreadedModules) {
288             PORT_SetError(SEC_ERROR_INCOMPATIBLE_PKCS11);
289             return SECFailure;
290         }
291         /* If we arrive here, the module failed a ThreadSafe init. */
292         mod->isThreadSafe = PR_FALSE;
293         if (!mod->libraryParams) {
294             pInitArgs = NULL;
295         } else {
296             moduleArgs = secmodNoLockArgs;
297             moduleArgs.LibraryParameters = (void *)mod->libraryParams;
298             pInitArgs = &moduleArgs;
299         }
300         crv = PK11_GETTAB(mod)->C_Initialize(pInitArgs);
301         if ((CKR_CRYPTOKI_ALREADY_INITIALIZED == crv) &&
302             (!enforceAlreadyInitializedError)) {
303             *alreadyLoaded = PR_TRUE;
304             return SECSuccess;
305         }
306         if (crv != CKR_OK) {
307             PORT_SetError(PK11_MapError(crv));
308             return SECFailure;
309         }
310     }
311     return SECSuccess;
312 }
313 
314 /*
315  * set the hasRootCerts flags in the module so it can be stored back
316  * into the database.
317  */
318 void
SECMOD_SetRootCerts(PK11SlotInfo * slot,SECMODModule * mod)319 SECMOD_SetRootCerts(PK11SlotInfo *slot, SECMODModule *mod)
320 {
321     PK11PreSlotInfo *psi = NULL;
322     int i;
323 
324     if (slot->hasRootCerts) {
325         for (i = 0; i < mod->slotInfoCount; i++) {
326             if (slot->slotID == mod->slotInfo[i].slotID) {
327                 psi = &mod->slotInfo[i];
328                 break;
329             }
330         }
331         if (psi == NULL) {
332             /* allocate more slots */
333             PK11PreSlotInfo *psi_list = (PK11PreSlotInfo *)
334                 PORT_ArenaAlloc(mod->arena,
335                                 (mod->slotInfoCount + 1) * sizeof(PK11PreSlotInfo));
336             /* copy the old ones */
337             if (mod->slotInfoCount > 0) {
338                 PORT_Memcpy(psi_list, mod->slotInfo,
339                             (mod->slotInfoCount) * sizeof(PK11PreSlotInfo));
340             }
341             /* assign psi to the last new slot */
342             psi = &psi_list[mod->slotInfoCount];
343             psi->slotID = slot->slotID;
344             psi->askpw = 0;
345             psi->timeout = 0;
346             psi->defaultFlags = 0;
347 
348             /* increment module count & store new list */
349             mod->slotInfo = psi_list;
350             mod->slotInfoCount++;
351         }
352         psi->hasRootCerts = 1;
353     }
354 }
355 
356 #ifndef NSS_TEST_BUILD
357 static const char *my_shlib_name =
358     SHLIB_PREFIX "nss" SHLIB_VERSION "." SHLIB_SUFFIX;
359 static const char *softoken_shlib_name =
360     SHLIB_PREFIX "softokn" SOFTOKEN_SHLIB_VERSION "." SHLIB_SUFFIX;
361 static const PRCallOnceType pristineCallOnce;
362 static PRCallOnceType loadSoftokenOnce;
363 static PRLibrary *softokenLib;
364 static PRInt32 softokenLoadCount;
365 
366 /* This function must be run only once. */
367 /*  determine if hybrid platform, then actually load the DSO. */
368 static PRStatus
softoken_LoadDSO(void)369 softoken_LoadDSO(void)
370 {
371     PRLibrary *handle;
372 
373     handle = PORT_LoadLibraryFromOrigin(my_shlib_name,
374                                         (PRFuncPtr)&softoken_LoadDSO,
375                                         softoken_shlib_name);
376     if (handle) {
377         softokenLib = handle;
378         return PR_SUCCESS;
379     }
380     return PR_FAILURE;
381 }
382 #else
383 CK_RV NSC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList);
384 char **NSC_ModuleDBFunc(unsigned long function, char *parameters, void *args);
385 #endif
386 
387 /*
388  * load a new module into our address space and initialize it.
389  */
390 SECStatus
secmod_LoadPKCS11Module(SECMODModule * mod,SECMODModule ** oldModule)391 secmod_LoadPKCS11Module(SECMODModule *mod, SECMODModule **oldModule)
392 {
393     PRLibrary *library = NULL;
394     CK_C_GetFunctionList entry = NULL;
395     CK_INFO info;
396     CK_ULONG slotCount = 0;
397     SECStatus rv;
398     PRBool alreadyLoaded = PR_FALSE;
399     char *disableUnload = NULL;
400 
401     if (mod->loaded)
402         return SECSuccess;
403 
404     /* internal modules get loaded from their internal list */
405     if (mod->internal && (mod->dllName == NULL)) {
406 #ifdef NSS_TEST_BUILD
407         entry = (CK_C_GetFunctionList)NSC_GetFunctionList;
408 #else
409         /*
410          * Loads softoken as a dynamic library,
411          * even though the rest of NSS assumes this as the "internal" module.
412          */
413         if (!softokenLib &&
414             PR_SUCCESS != PR_CallOnce(&loadSoftokenOnce, &softoken_LoadDSO))
415             return SECFailure;
416 
417         PR_ATOMIC_INCREMENT(&softokenLoadCount);
418 
419         if (mod->isFIPS) {
420             entry = (CK_C_GetFunctionList)
421                 PR_FindSymbol(softokenLib, "FC_GetFunctionList");
422         } else {
423             entry = (CK_C_GetFunctionList)
424                 PR_FindSymbol(softokenLib, "NSC_GetFunctionList");
425         }
426 
427         if (!entry)
428             return SECFailure;
429 #endif
430 
431         if (mod->isModuleDB) {
432             mod->moduleDBFunc = (CK_C_GetFunctionList)
433 #ifdef NSS_TEST_BUILD
434                 NSC_ModuleDBFunc;
435 #else
436                 PR_FindSymbol(softokenLib, "NSC_ModuleDBFunc");
437 #endif
438         }
439 
440         if (mod->moduleDBOnly) {
441             mod->loaded = PR_TRUE;
442             return SECSuccess;
443         }
444     } else {
445         /* Not internal, load the DLL and look up C_GetFunctionList */
446         if (mod->dllName == NULL) {
447             return SECFailure;
448         }
449 
450         /* load the library. If this succeeds, then we have to remember to
451          * unload the library if anything goes wrong from here on out...
452          */
453         library = PR_LoadLibrary(mod->dllName);
454         mod->library = (void *)library;
455 
456         if (library == NULL) {
457             return SECFailure;
458         }
459 
460         /*
461          * now we need to get the entry point to find the function pointers
462          */
463         if (!mod->moduleDBOnly) {
464             entry = (CK_C_GetFunctionList)
465                 PR_FindSymbol(library, "C_GetFunctionList");
466         }
467         if (mod->isModuleDB) {
468             mod->moduleDBFunc = (void *)
469                 PR_FindSymbol(library, "NSS_ReturnModuleSpecData");
470         }
471         if (mod->moduleDBFunc == NULL)
472             mod->isModuleDB = PR_FALSE;
473         if (entry == NULL) {
474             if (mod->isModuleDB) {
475                 mod->loaded = PR_TRUE;
476                 mod->moduleDBOnly = PR_TRUE;
477                 return SECSuccess;
478             }
479             PR_UnloadLibrary(library);
480             return SECFailure;
481         }
482     }
483 
484     /*
485      * We need to get the function list
486      */
487     if ((*entry)((CK_FUNCTION_LIST_PTR *)&mod->functionList) != CKR_OK)
488         goto fail;
489 
490 #ifdef DEBUG_MODULE
491     if (PR_TRUE) {
492         modToDBG = PR_GetEnvSecure("NSS_DEBUG_PKCS11_MODULE");
493         if (modToDBG && strcmp(mod->commonName, modToDBG) == 0) {
494             mod->functionList = (void *)nss_InsertDeviceLog(
495                 (CK_FUNCTION_LIST_PTR)mod->functionList);
496         }
497     }
498 #endif
499 
500     mod->isThreadSafe = PR_TRUE;
501 
502     /* Now we initialize the module */
503     rv = secmod_ModuleInit(mod, oldModule, &alreadyLoaded);
504     if (rv != SECSuccess) {
505         goto fail;
506     }
507 
508     /* module has been reloaded, this module itself is done,
509      * return to the caller */
510     if (mod->functionList == NULL) {
511         mod->loaded = PR_TRUE; /* technically the module is loaded.. */
512         return SECSuccess;
513     }
514 
515     /* check the version number */
516     if (PK11_GETTAB(mod)->C_GetInfo(&info) != CKR_OK)
517         goto fail2;
518     if (info.cryptokiVersion.major != 2)
519         goto fail2;
520     /* all 2.0 are a priori *not* thread safe */
521     if (info.cryptokiVersion.minor < 1) {
522         if (!loadSingleThreadedModules) {
523             PORT_SetError(SEC_ERROR_INCOMPATIBLE_PKCS11);
524             goto fail2;
525         } else {
526             mod->isThreadSafe = PR_FALSE;
527         }
528     }
529     mod->cryptokiVersion = info.cryptokiVersion;
530 
531     /* If we don't have a common name, get it from the PKCS 11 module */
532     if ((mod->commonName == NULL) || (mod->commonName[0] == 0)) {
533         mod->commonName = PK11_MakeString(mod->arena, NULL,
534                                           (char *)info.libraryDescription, sizeof(info.libraryDescription));
535         if (mod->commonName == NULL)
536             goto fail2;
537     }
538 
539     /* initialize the Slots */
540     if (PK11_GETTAB(mod)->C_GetSlotList(CK_FALSE, NULL, &slotCount) == CKR_OK) {
541         CK_SLOT_ID *slotIDs;
542         int i;
543         CK_RV crv;
544 
545         mod->slots = (PK11SlotInfo **)PORT_ArenaAlloc(mod->arena,
546                                                       sizeof(PK11SlotInfo *) * slotCount);
547         if (mod->slots == NULL)
548             goto fail2;
549 
550         slotIDs = (CK_SLOT_ID *)PORT_Alloc(sizeof(CK_SLOT_ID) * slotCount);
551         if (slotIDs == NULL) {
552             goto fail2;
553         }
554         crv = PK11_GETTAB(mod)->C_GetSlotList(CK_FALSE, slotIDs, &slotCount);
555         if (crv != CKR_OK) {
556             PORT_Free(slotIDs);
557             goto fail2;
558         }
559 
560         /* Initialize each slot */
561         for (i = 0; i < (int)slotCount; i++) {
562             mod->slots[i] = PK11_NewSlotInfo(mod);
563             PK11_InitSlot(mod, slotIDs[i], mod->slots[i]);
564             /* look down the slot info table */
565             PK11_LoadSlotList(mod->slots[i], mod->slotInfo, mod->slotInfoCount);
566             SECMOD_SetRootCerts(mod->slots[i], mod);
567             /* explicitly mark the internal slot as such if IsInternalKeySlot()
568              * is set */
569             if (secmod_IsInternalKeySlot(mod) && (i == (mod->isFIPS ? 0 : 1))) {
570                 pk11_SetInternalKeySlotIfFirst(mod->slots[i]);
571             }
572         }
573         mod->slotCount = slotCount;
574         mod->slotInfoCount = 0;
575         PORT_Free(slotIDs);
576     }
577 
578     mod->loaded = PR_TRUE;
579     mod->moduleID = nextModuleID++;
580     return SECSuccess;
581 fail2:
582     if (enforceAlreadyInitializedError || (!alreadyLoaded)) {
583         PK11_GETTAB(mod)->C_Finalize(NULL);
584     }
585 fail:
586     mod->functionList = NULL;
587     disableUnload = PR_GetEnvSecure("NSS_DISABLE_UNLOAD");
588     if (library && !disableUnload) {
589         PR_UnloadLibrary(library);
590     }
591     return SECFailure;
592 }
593 
594 SECStatus
SECMOD_UnloadModule(SECMODModule * mod)595 SECMOD_UnloadModule(SECMODModule *mod)
596 {
597     PRLibrary *library;
598     char *disableUnload = NULL;
599 
600     if (!mod->loaded) {
601         return SECFailure;
602     }
603     if (finalizeModules) {
604         if (mod->functionList && !mod->moduleDBOnly) {
605             PK11_GETTAB(mod)->C_Finalize(NULL);
606         }
607     }
608     mod->moduleID = 0;
609     mod->loaded = PR_FALSE;
610 
611     /* do we want the semantics to allow unloading the internal library?
612      * if not, we should change this to SECFailure and move it above the
613      * mod->loaded = PR_FALSE; */
614     if (mod->internal && (mod->dllName == NULL)) {
615 #ifndef NSS_TEST_BUILD
616         if (0 == PR_ATOMIC_DECREMENT(&softokenLoadCount)) {
617             if (softokenLib) {
618                 disableUnload = PR_GetEnvSecure("NSS_DISABLE_UNLOAD");
619                 if (!disableUnload) {
620 #ifdef DEBUG
621                     PRStatus status = PR_UnloadLibrary(softokenLib);
622                     PORT_Assert(PR_SUCCESS == status);
623 #else
624                     PR_UnloadLibrary(softokenLib);
625 #endif
626                 }
627                 softokenLib = NULL;
628             }
629             loadSoftokenOnce = pristineCallOnce;
630         }
631 #endif
632         return SECSuccess;
633     }
634 
635     library = (PRLibrary *)mod->library;
636     /* paranoia */
637     if (library == NULL) {
638         return SECFailure;
639     }
640 
641     disableUnload = PR_GetEnvSecure("NSS_DISABLE_UNLOAD");
642     if (!disableUnload) {
643         PR_UnloadLibrary(library);
644     }
645     return SECSuccess;
646 }
647 
648 void
nss_DumpModuleLog(void)649 nss_DumpModuleLog(void)
650 {
651 #ifdef DEBUG_MODULE
652     if (modToDBG) {
653         print_final_statistics();
654     }
655 #endif
656 }
657