security/nss/lib/pk11wrap/pk11slot.c

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

     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  * Deal with PKCS #11 Slots.
     6  */
     7 #include "seccomon.h"
     8 #include "secmod.h"
     9 #include "nssilock.h"
    10 #include "secmodi.h"
    11 #include "secmodti.h"
    12 #include "pkcs11t.h"
    13 #include "pk11func.h"
    14 #include "secitem.h"
    15 #include "secerr.h"
    17 #include "dev.h" 
    18 #include "dev3hack.h" 
    19 #include "pkim.h"
    20 #include "utilpars.h"
    23 /*************************************************************
    24  * local static and global data
    25  *************************************************************/
    27 /*
    28  * This array helps parsing between names, mechanisms, and flags.
    29  * to make the config files understand more entries, add them
    30  * to this table.
    31  */
    32 const PK11DefaultArrayEntry PK11_DefaultArray[] = {
    33 	{ "RSA", SECMOD_RSA_FLAG, CKM_RSA_PKCS },
    34 	{ "DSA", SECMOD_DSA_FLAG, CKM_DSA },
    35 	{ "ECC", SECMOD_ECC_FLAG, CKM_ECDSA },
    36 	{ "DH", SECMOD_DH_FLAG, CKM_DH_PKCS_DERIVE },
    37 	{ "RC2", SECMOD_RC2_FLAG, CKM_RC2_CBC },
    38 	{ "RC4", SECMOD_RC4_FLAG, CKM_RC4 },
    39 	{ "DES", SECMOD_DES_FLAG, CKM_DES_CBC },
    40 	{ "AES", SECMOD_AES_FLAG, CKM_AES_CBC },
    41 	{ "Camellia", SECMOD_CAMELLIA_FLAG, CKM_CAMELLIA_CBC },
    42 	{ "SEED", SECMOD_SEED_FLAG, CKM_SEED_CBC },
    43 	{ "RC5", SECMOD_RC5_FLAG, CKM_RC5_CBC },
    44 	{ "SHA-1", SECMOD_SHA1_FLAG, CKM_SHA_1 },
    45 /*	{ "SHA224", SECMOD_SHA256_FLAG, CKM_SHA224 }, */
    46 	{ "SHA256", SECMOD_SHA256_FLAG, CKM_SHA256 },
    47 /*	{ "SHA384", SECMOD_SHA512_FLAG, CKM_SHA384 }, */
    48 	{ "SHA512", SECMOD_SHA512_FLAG, CKM_SHA512 },
    49 	{ "MD5", SECMOD_MD5_FLAG, CKM_MD5 },
    50 	{ "MD2", SECMOD_MD2_FLAG, CKM_MD2 },
    51 	{ "SSL", SECMOD_SSL_FLAG, CKM_SSL3_PRE_MASTER_KEY_GEN },
    52 	{ "TLS", SECMOD_TLS_FLAG, CKM_TLS_MASTER_KEY_DERIVE },
    53 	{ "SKIPJACK", SECMOD_FORTEZZA_FLAG, CKM_SKIPJACK_CBC64 },
    54 	{ "Publicly-readable certs", SECMOD_FRIENDLY_FLAG, CKM_INVALID_MECHANISM },
    55 	{ "Random Num Generator", SECMOD_RANDOM_FLAG, CKM_FAKE_RANDOM },
    56 };
    57 const int num_pk11_default_mechanisms = 
    58                 sizeof(PK11_DefaultArray) / sizeof(PK11_DefaultArray[0]);
    60 const PK11DefaultArrayEntry *
    61 PK11_GetDefaultArray(int *size)
    62 {
    63     if (size) {
    64 	*size = num_pk11_default_mechanisms;
    65     }
    66     return PK11_DefaultArray;
    67 }
    69 /*
    70  * These  slotlists are lists of modules which provide default support for
    71  *  a given algorithm or mechanism.
    72  */
    73 static PK11SlotList 
    74     pk11_seedSlotList,
    75     pk11_camelliaSlotList,
    76     pk11_aesSlotList,
    77     pk11_desSlotList,
    78     pk11_rc4SlotList,
    79     pk11_rc2SlotList,
    80     pk11_rc5SlotList,
    81     pk11_sha1SlotList,
    82     pk11_md5SlotList,
    83     pk11_md2SlotList,
    84     pk11_rsaSlotList,
    85     pk11_dsaSlotList,
    86     pk11_dhSlotList,
    87     pk11_ecSlotList,
    88     pk11_ideaSlotList,
    89     pk11_sslSlotList,
    90     pk11_tlsSlotList,
    91     pk11_randomSlotList,
    92     pk11_sha256SlotList,
    93     pk11_sha512SlotList;	/* slots do SHA512 and SHA384 */
    95 /************************************************************
    96  * Generic Slot List and Slot List element manipulations
    97  ************************************************************/
    99 /*
   100  * allocate a new list 
   101  */
   102 PK11SlotList *
   103 PK11_NewSlotList(void)
   104 {
   105     PK11SlotList *list;
   107     list = (PK11SlotList *)PORT_Alloc(sizeof(PK11SlotList));
   108     if (list == NULL) return NULL;
   109     list->head = NULL;
   110     list->tail = NULL;
   111     list->lock = PZ_NewLock(nssILockList);
   112     if (list->lock == NULL) {
   113 	PORT_Free(list);
   114 	return NULL;
   115     }
   117     return list;
   118 }
   120 /*
   121  * free a list element when all the references go away.
   122  */
   123 SECStatus
   124 PK11_FreeSlotListElement(PK11SlotList *list, PK11SlotListElement *le)
   125 {
   126     PRBool freeit = PR_FALSE;
   128     if (list == NULL || le == NULL) {
   129 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   130 	return SECFailure;
   131     }
   133     PZ_Lock(list->lock);
   134     if (le->refCount-- == 1) {
   135 	freeit = PR_TRUE;
   136     }
   137     PZ_Unlock(list->lock);
   138     if (freeit) {
   139     	PK11_FreeSlot(le->slot);
   140 	PORT_Free(le);
   141     }
   142     return SECSuccess;
   143 }
   145 static void
   146 pk11_FreeSlotListStatic(PK11SlotList *list)
   147 {
   148     PK11SlotListElement *le, *next ;
   149     if (list == NULL) return;
   151     for (le = list->head ; le; le = next) {
   152 	next = le->next;
   153 	PK11_FreeSlotListElement(list,le);
   154     }
   155     if (list->lock) {
   156     	PZ_DestroyLock(list->lock);
   157     }
   158     list->lock = NULL;
   159     list->head = NULL;
   160 }
   162 /*
   163  * if we are freeing the list, we must be the only ones with a pointer
   164  * to the list.
   165  */
   166 void
   167 PK11_FreeSlotList(PK11SlotList *list)
   168 {
   169     pk11_FreeSlotListStatic(list);
   170     PORT_Free(list);
   171 }
   173 /*
   174  * add a slot to a list
   175  * "slot" is the slot to be added. Ownership is not transferred.
   176  * "sorted" indicates whether or not the slot should be inserted according to
   177  *   cipherOrder of the associated module. PR_FALSE indicates that the slot
   178  *   should be inserted to the head of the list.
   179  */
   180 SECStatus
   181 PK11_AddSlotToList(PK11SlotList *list,PK11SlotInfo *slot, PRBool sorted)
   182 {
   183     PK11SlotListElement *le;
   184     PK11SlotListElement *element;
   186     le = (PK11SlotListElement *) PORT_Alloc(sizeof(PK11SlotListElement));
   187     if (le == NULL) return SECFailure;
   189     le->slot = PK11_ReferenceSlot(slot);
   190     le->prev = NULL;
   191     le->refCount = 1;
   192     PZ_Lock(list->lock);
   193     element = list->head;
   194     /* Insertion sort, with higher cipherOrders are sorted first in the list */
   195     while (element && sorted && (element->slot->module->cipherOrder >
   196                                  le->slot->module->cipherOrder)) {
   197         element = element->next;
   198     }
   199     if (element) {
   200         le->prev = element->prev;
   201         element->prev = le;
   202         le->next = element;
   203     } else {
   204         le->prev = list->tail;
   205         le->next = NULL;
   206         list->tail = le;
   207     }
   208     if (le->prev) le->prev->next = le;
   209     if (list->head == element) list->head = le;
   210     PZ_Unlock(list->lock);
   212     return SECSuccess;
   213 }
   215 /*
   216  * remove a slot entry from the list
   217  */
   218 SECStatus
   219 PK11_DeleteSlotFromList(PK11SlotList *list,PK11SlotListElement *le)
   220 {
   221     PZ_Lock(list->lock);
   222     if (le->prev) le->prev->next = le->next; else list->head = le->next;
   223     if (le->next) le->next->prev = le->prev; else list->tail = le->prev;
   224     le->next = le->prev = NULL;
   225     PZ_Unlock(list->lock);
   226     PK11_FreeSlotListElement(list,le);
   227     return SECSuccess;
   228 }
   230 /*
   231  * Move a list to the end of the target list.
   232  * NOTE: There is no locking here... This assumes BOTH lists are private copy
   233  * lists. It also does not re-sort the target list.
   234  */
   235 SECStatus
   236 pk11_MoveListToList(PK11SlotList *target,PK11SlotList *src)
   237 {
   238     if (src->head == NULL) return SECSuccess;
   240     if (target->tail == NULL) {
   241 	target->head = src->head;
   242     } else {
   243 	target->tail->next = src->head;
   244     }
   245     src->head->prev = target->tail;
   246     target->tail = src->tail;
   247     src->head = src->tail = NULL;
   248     return SECSuccess;
   249 }
   251 /*
   252  * get an element from the list with a reference. You must own the list.
   253  */
   254 PK11SlotListElement *
   255 PK11_GetFirstRef(PK11SlotList *list)
   256 {
   257     PK11SlotListElement *le;
   259     le = list->head;
   260     if (le != NULL) (le)->refCount++;
   261     return le;
   262 }
   264 /*
   265  * get the next element from the list with a reference. You must own the list.
   266  */
   267 PK11SlotListElement *
   268 PK11_GetNextRef(PK11SlotList *list, PK11SlotListElement *le, PRBool restart)
   269 {
   270     PK11SlotListElement *new_le;
   271     new_le = le->next;
   272     if (new_le) new_le->refCount++;
   273     PK11_FreeSlotListElement(list,le);
   274     return new_le;
   275 }
   277 /*
   278  * get an element safely from the list. This just makes sure that if
   279  * this element is not deleted while we deal with it.
   280  */
   281 PK11SlotListElement *
   282 PK11_GetFirstSafe(PK11SlotList *list)
   283 {
   284     PK11SlotListElement *le;
   286     PZ_Lock(list->lock);
   287     le = list->head;
   288     if (le != NULL) (le)->refCount++;
   289     PZ_Unlock(list->lock);
   290     return le;
   291 }
   293 /*
   294  * NOTE: if this element gets deleted, we can no longer safely traverse using
   295  * it's pointers. We can either terminate the loop, or restart from the
   296  * beginning. This is controlled by the restart option.
   297  */
   298 PK11SlotListElement *
   299 PK11_GetNextSafe(PK11SlotList *list, PK11SlotListElement *le, PRBool restart)
   300 {
   301     PK11SlotListElement *new_le;
   302     PZ_Lock(list->lock);
   303     new_le = le->next;
   304     if (le->next == NULL) {
   305 	/* if the prev and next fields are NULL then either this element
   306 	 * has been removed and we need to walk the list again (if restart
   307 	 * is true) or this was the only element on the list */
   308 	if ((le->prev == NULL) && restart &&  (list->head != le)) {
   309 	    new_le = list->head;
   310 	}
   311     }
   312     if (new_le) new_le->refCount++;
   313     PZ_Unlock(list->lock);
   314     PK11_FreeSlotListElement(list,le);
   315     return new_le;
   316 }
   319 /*
   320  * Find the element that holds this slot
   321  */
   322 PK11SlotListElement *
   323 PK11_FindSlotElement(PK11SlotList *list,PK11SlotInfo *slot)
   324 {
   325     PK11SlotListElement *le;
   327     for (le = PK11_GetFirstSafe(list); le;
   328 			 	le = PK11_GetNextSafe(list,le,PR_TRUE)) {
   329 	if (le->slot == slot) return le;
   330     }
   331     return NULL;
   332 }
   334 /************************************************************
   335  * Generic Slot Utilities
   336  ************************************************************/
   337 /*
   338  * Create a new slot structure
   339  */
   340 PK11SlotInfo *
   341 PK11_NewSlotInfo(SECMODModule *mod)
   342 {
   343     PK11SlotInfo *slot;
   345     slot = (PK11SlotInfo *)PORT_Alloc(sizeof(PK11SlotInfo));
   346     if (slot == NULL) return slot;
   348     slot->sessionLock = mod->isThreadSafe ?
   349 	PZ_NewLock(nssILockSession) : mod->refLock;
   350     if (slot->sessionLock == NULL) {
   351 	PORT_Free(slot);
   352 	return NULL;
   353     }
   354     slot->freeListLock = PZ_NewLock(nssILockFreelist);
   355     if (slot->freeListLock == NULL) {
   356 	if (mod->isThreadSafe) {
   357 	    PZ_DestroyLock(slot->sessionLock);
   358 	}
   359 	PORT_Free(slot);
   360 	return NULL;
   361     }
   362     slot->freeSymKeysWithSessionHead = NULL;
   363     slot->freeSymKeysHead = NULL;
   364     slot->keyCount = 0;
   365     slot->maxKeyCount = 0;
   366     slot->functionList = NULL;
   367     slot->needTest = PR_TRUE;
   368     slot->isPerm = PR_FALSE;
   369     slot->isHW = PR_FALSE;
   370     slot->isInternal = PR_FALSE;
   371     slot->isThreadSafe = PR_FALSE;
   372     slot->disabled = PR_FALSE;
   373     slot->series = 1;
   374     slot->wrapKey = 0;
   375     slot->wrapMechanism = CKM_INVALID_MECHANISM;
   376     slot->refKeys[0] = CK_INVALID_HANDLE;
   377     slot->reason = PK11_DIS_NONE;
   378     slot->readOnly = PR_TRUE;
   379     slot->needLogin = PR_FALSE;
   380     slot->hasRandom = PR_FALSE;
   381     slot->defRWSession = PR_FALSE;
   382     slot->protectedAuthPath = PR_FALSE;
   383     slot->flags = 0;
   384     slot->session = CK_INVALID_SESSION;
   385     slot->slotID = 0;
   386     slot->defaultFlags = 0;
   387     slot->refCount = 1;
   388     slot->askpw = 0;
   389     slot->timeout = 0;
   390     slot->mechanismList = NULL;
   391     slot->mechanismCount = 0;
   392     slot->cert_array = NULL;
   393     slot->cert_count = 0;
   394     slot->slot_name[0] = 0;
   395     slot->token_name[0] = 0;
   396     PORT_Memset(slot->serial,' ',sizeof(slot->serial));
   397     slot->module = NULL;
   398     slot->authTransact = 0;
   399     slot->authTime = LL_ZERO;
   400     slot->minPassword = 0;
   401     slot->maxPassword = 0;
   402     slot->hasRootCerts = PR_FALSE;
   403     slot->nssToken = NULL;
   404     return slot;
   405 }
   407 /* create a new reference to a slot so it doesn't go away */
   408 PK11SlotInfo *
   409 PK11_ReferenceSlot(PK11SlotInfo *slot)
   410 {
   411     PR_ATOMIC_INCREMENT(&slot->refCount);
   412     return slot;
   413 }
   415 /* Destroy all info on a slot we have built up */
   416 void
   417 PK11_DestroySlot(PK11SlotInfo *slot)
   418 {
   419    /* free up the cached keys and sessions */
   420    PK11_CleanKeyList(slot);
   422    /* free up all the sessions on this slot */
   423    if (slot->functionList) {
   424 	PK11_GETTAB(slot)->C_CloseAllSessions(slot->slotID);
   425    }
   427    if (slot->mechanismList) {
   428 	PORT_Free(slot->mechanismList);
   429    }
   430    if (slot->isThreadSafe && slot->sessionLock) {
   431 	PZ_DestroyLock(slot->sessionLock);
   432    }
   433    slot->sessionLock = NULL;
   434    if (slot->freeListLock) {
   435 	PZ_DestroyLock(slot->freeListLock);
   436 	slot->freeListLock = NULL;
   437    }
   439    /* finally Tell our parent module that we've gone away so it can unload */
   440    if (slot->module) {
   441 	SECMOD_SlotDestroyModule(slot->module,PR_TRUE);
   442    }
   444    /* ok, well not quit finally... now we free the memory */
   445    PORT_Free(slot);
   446 }
   449 /* We're all done with the slot, free it */
   450 void
   451 PK11_FreeSlot(PK11SlotInfo *slot)
   452 {
   453     if (PR_ATOMIC_DECREMENT(&slot->refCount) == 0) {
   454 	PK11_DestroySlot(slot);
   455     }
   456 }
   458 void
   459 PK11_EnterSlotMonitor(PK11SlotInfo *slot) {
   460     PZ_Lock(slot->sessionLock);
   461 }
   463 void
   464 PK11_ExitSlotMonitor(PK11SlotInfo *slot) {
   465     PZ_Unlock(slot->sessionLock);
   466 }
   468 /***********************************************************
   469  * Functions to find specific slots.
   470  ***********************************************************/
   471 PRBool
   472 SECMOD_HasRootCerts(void)
   473 {
   474    SECMODModuleList *mlp;
   475    SECMODModuleList *modules;
   476    SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
   477    int i;
   478    PRBool found = PR_FALSE;
   480     if (!moduleLock) {
   481     	PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
   482 	return found;
   483     }
   485    /* work through all the slots */
   486    SECMOD_GetReadLock(moduleLock);
   487    modules = SECMOD_GetDefaultModuleList();
   488    for(mlp = modules; mlp != NULL; mlp = mlp->next) {
   489 	for (i=0; i < mlp->module->slotCount; i++) {
   490 	    PK11SlotInfo *tmpSlot = mlp->module->slots[i];
   491 	    if (PK11_IsPresent(tmpSlot)) {
   492 		if (tmpSlot->hasRootCerts) {
   493 		    found = PR_TRUE;
   494 		    break;
   495 		}
   496 	    }
   497 	}
   498 	if (found) break;
   499     }
   500     SECMOD_ReleaseReadLock(moduleLock);
   502     return found;
   503 }
   505 /***********************************************************
   506  * Functions to find specific slots.
   507  ***********************************************************/
   508 PK11SlotList *
   509 PK11_FindSlotsByNames(const char *dllName, const char* slotName,
   510                         const char* tokenName, PRBool presentOnly)
   511 {
   512     SECMODModuleList *mlp;
   513     SECMODModuleList *modules;
   514     SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
   515     int i;
   516     PK11SlotList* slotList = NULL;
   517     PRUint32 slotcount = 0;
   518     SECStatus rv = SECSuccess;
   520     if (!moduleLock) {
   521     	PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
   522 	return slotList;
   523     }
   525     slotList = PK11_NewSlotList();
   526     if (!slotList) {
   527         PORT_SetError(SEC_ERROR_NO_MEMORY);
   528         return slotList;
   529     }
   531     if ( ((NULL == dllName) || (0 == *dllName)) &&
   532         ((NULL == slotName) || (0 == *slotName)) &&
   533         ((NULL == tokenName) || (0 == *tokenName)) ) {
   534         /* default to softoken */
   535         PK11_AddSlotToList(slotList, PK11_GetInternalKeySlot(), PR_TRUE);
   536         return slotList;
   537     }
   539     /* work through all the slots */
   540     SECMOD_GetReadLock(moduleLock);
   541     modules = SECMOD_GetDefaultModuleList();
   542     for (mlp = modules; mlp != NULL; mlp = mlp->next) {
   543         PORT_Assert(mlp->module);
   544         if (!mlp->module) {
   545             rv = SECFailure;
   546             break;
   547         }
   548         if ((!dllName) || (mlp->module->dllName &&
   549             (0 == PORT_Strcmp(mlp->module->dllName, dllName)))) {
   550             for (i=0; i < mlp->module->slotCount; i++) {
   551                 PK11SlotInfo *tmpSlot = (mlp->module->slots?mlp->module->slots[i]:NULL);
   552                 PORT_Assert(tmpSlot);
   553                 if (!tmpSlot) {
   554                     rv = SECFailure;
   555                     break;
   556                 }
   557                 if ((PR_FALSE == presentOnly || PK11_IsPresent(tmpSlot)) &&
   558                     ( (!tokenName) || (tmpSlot->token_name &&
   559                     (0==PORT_Strcmp(tmpSlot->token_name, tokenName)))) &&
   560                     ( (!slotName) || (tmpSlot->slot_name &&
   561                     (0==PORT_Strcmp(tmpSlot->slot_name, slotName)))) ) {
   562                     if (tmpSlot) {
   563                         PK11_AddSlotToList(slotList, tmpSlot, PR_TRUE);
   564                         slotcount++;
   565                     }
   566                 }
   567             }
   568         }
   569     }
   570     SECMOD_ReleaseReadLock(moduleLock);
   572     if ( (0 == slotcount) || (SECFailure == rv) ) {
   573         PORT_SetError(SEC_ERROR_NO_TOKEN);
   574         PK11_FreeSlotList(slotList);
   575         slotList = NULL;
   576     }
   578     if (SECFailure == rv) {
   579         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   580     }
   582     return slotList;
   583 }
   585 PK11SlotInfo *
   586 PK11_FindSlotByName(const char *name)
   587 {
   588    SECMODModuleList *mlp;
   589    SECMODModuleList *modules;
   590    SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
   591    int i;
   592    PK11SlotInfo *slot = NULL;
   594     if (!moduleLock) {
   595     	PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
   596 	return slot;
   597     }
   598    if ((name == NULL) || (*name == 0)) {
   599 	return PK11_GetInternalKeySlot();
   600    }
   602    /* work through all the slots */
   603    SECMOD_GetReadLock(moduleLock);
   604    modules = SECMOD_GetDefaultModuleList();
   605    for(mlp = modules; mlp != NULL; mlp = mlp->next) {
   606 	for (i=0; i < mlp->module->slotCount; i++) {
   607 	    PK11SlotInfo *tmpSlot = mlp->module->slots[i];
   608 	    if (PK11_IsPresent(tmpSlot)) {
   609 		if (PORT_Strcmp(tmpSlot->token_name,name) == 0) {
   610 		    slot = PK11_ReferenceSlot(tmpSlot);
   611 		    break;
   612 		}
   613 	    }
   614 	}
   615 	if (slot != NULL) break;
   616     }
   617     SECMOD_ReleaseReadLock(moduleLock);
   619     if (slot == NULL) {
   620 	PORT_SetError(SEC_ERROR_NO_TOKEN);
   621     }
   623     return slot;
   624 }
   627 PK11SlotInfo *
   628 PK11_FindSlotBySerial(char *serial)
   629 {
   630    SECMODModuleList *mlp;
   631    SECMODModuleList *modules;
   632    SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
   633    int i;
   634    PK11SlotInfo *slot = NULL;
   636     if (!moduleLock) {
   637     	PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
   638 	return slot;
   639     }
   640    /* work through all the slots */
   641    SECMOD_GetReadLock(moduleLock);
   642    modules = SECMOD_GetDefaultModuleList();
   643    for(mlp = modules; mlp != NULL; mlp = mlp->next) {
   644 	for (i=0; i < mlp->module->slotCount; i++) {
   645 	    PK11SlotInfo *tmpSlot = mlp->module->slots[i];
   646 	    if (PK11_IsPresent(tmpSlot)) {
   647 		if (PORT_Memcmp(tmpSlot->serial,serial,
   648 					sizeof(tmpSlot->serial)) == 0) {
   649 		    slot = PK11_ReferenceSlot(tmpSlot);
   650 		    break;
   651 		}
   652 	    }
   653 	}
   654 	if (slot != NULL) break;
   655     }
   656     SECMOD_ReleaseReadLock(moduleLock);
   658     if (slot == NULL) {
   659 	PORT_SetError(SEC_ERROR_NO_TOKEN);
   660     }
   662     return slot;
   663 }
   665 /*
   666  * notification stub. If we ever get interested in any events that
   667  * the pkcs11 functions may pass back to use, we can catch them here...
   668  * currently pdata is a slotinfo structure.
   669  */
   670 CK_RV pk11_notify(CK_SESSION_HANDLE session, CK_NOTIFICATION event,
   671 							 CK_VOID_PTR pdata)
   672 {
   673     return CKR_OK;
   674 }
   676 /*
   677  * grab a new RW session
   678  * !!! has a side effect of grabbing the Monitor if either the slot's default
   679  * session is RW or the slot is not thread safe. Monitor is release in function
   680  * below
   681  */
   682 CK_SESSION_HANDLE PK11_GetRWSession(PK11SlotInfo *slot)
   683 {
   684     CK_SESSION_HANDLE rwsession;
   685     CK_RV crv;
   686     PRBool haveMonitor = PR_FALSE;
   688     if (!slot->isThreadSafe || slot->defRWSession) {
   689     	PK11_EnterSlotMonitor(slot);
   690 	haveMonitor = PR_TRUE;
   691     }
   692     if (slot->defRWSession) {
   693 	PORT_Assert(slot->session != CK_INVALID_SESSION);
   694 	if (slot->session != CK_INVALID_SESSION) 
   695 	    return slot->session;
   696     }
   698     crv = PK11_GETTAB(slot)->C_OpenSession(slot->slotID,
   699 				CKF_RW_SESSION|CKF_SERIAL_SESSION,
   700 				  	  slot, pk11_notify,&rwsession);
   701     PORT_Assert(rwsession != CK_INVALID_SESSION || crv != CKR_OK);
   702     if (crv != CKR_OK || rwsession == CK_INVALID_SESSION) {
   703 	if (crv == CKR_OK) 
   704 	    crv = CKR_DEVICE_ERROR;
   705 	if (haveMonitor)
   706 	    PK11_ExitSlotMonitor(slot);
   707 	PORT_SetError(PK11_MapError(crv));
   708 	return CK_INVALID_SESSION;
   709     }
   710     if (slot->defRWSession) { /* we have the monitor */
   711     	slot->session = rwsession;
   712     }
   713     return rwsession;
   714 }
   716 PRBool
   717 PK11_RWSessionHasLock(PK11SlotInfo *slot,CK_SESSION_HANDLE session_handle) 
   718 {
   719     PRBool hasLock;
   720     hasLock = (PRBool)(!slot->isThreadSafe || 
   721     	      (slot->defRWSession && slot->session != CK_INVALID_SESSION));
   722     return hasLock;
   723 }
   725 static PRBool
   726 pk11_RWSessionIsDefault(PK11SlotInfo *slot,CK_SESSION_HANDLE rwsession)
   727 {
   728     PRBool isDefault;
   729     isDefault = (PRBool)(slot->session == rwsession &&
   730     	                 slot->defRWSession && 
   731 			 slot->session != CK_INVALID_SESSION);
   732     return isDefault;
   733 }
   735 /*
   736  * close the rwsession and restore our readonly session
   737  * !!! has a side effect of releasing the Monitor if either the slot's default
   738  * session is RW or the slot is not thread safe.
   739  */
   740 void
   741 PK11_RestoreROSession(PK11SlotInfo *slot,CK_SESSION_HANDLE rwsession)
   742 {
   743     PORT_Assert(rwsession != CK_INVALID_SESSION);
   744     if (rwsession != CK_INVALID_SESSION) {
   745     	PRBool doExit = PK11_RWSessionHasLock(slot, rwsession);
   746 	if (!pk11_RWSessionIsDefault(slot, rwsession))
   747 	    PK11_GETTAB(slot)->C_CloseSession(rwsession);
   748 	if (doExit)
   749 	    PK11_ExitSlotMonitor(slot);
   750     }
   751 }
   753 /************************************************************
   754  * Manage the built-In Slot Lists
   755  ************************************************************/
   757 /* Init the static built int slot list (should actually integrate
   758  * with PK11_NewSlotList */
   759 static void
   760 pk11_InitSlotListStatic(PK11SlotList *list)
   761 {
   762     list->lock = PZ_NewLock(nssILockList);
   763     list->head = NULL;
   764 }
   767 /* initialize the system slotlists */
   768 SECStatus
   769 PK11_InitSlotLists(void)
   770 {
   771     pk11_InitSlotListStatic(&pk11_seedSlotList);
   772     pk11_InitSlotListStatic(&pk11_camelliaSlotList);
   773     pk11_InitSlotListStatic(&pk11_aesSlotList);
   774     pk11_InitSlotListStatic(&pk11_desSlotList);
   775     pk11_InitSlotListStatic(&pk11_rc4SlotList);
   776     pk11_InitSlotListStatic(&pk11_rc2SlotList);
   777     pk11_InitSlotListStatic(&pk11_rc5SlotList);
   778     pk11_InitSlotListStatic(&pk11_md5SlotList);
   779     pk11_InitSlotListStatic(&pk11_md2SlotList);
   780     pk11_InitSlotListStatic(&pk11_sha1SlotList);
   781     pk11_InitSlotListStatic(&pk11_rsaSlotList);
   782     pk11_InitSlotListStatic(&pk11_dsaSlotList);
   783     pk11_InitSlotListStatic(&pk11_dhSlotList);
   784     pk11_InitSlotListStatic(&pk11_ecSlotList);
   785     pk11_InitSlotListStatic(&pk11_ideaSlotList);
   786     pk11_InitSlotListStatic(&pk11_sslSlotList);
   787     pk11_InitSlotListStatic(&pk11_tlsSlotList);
   788     pk11_InitSlotListStatic(&pk11_randomSlotList);
   789     pk11_InitSlotListStatic(&pk11_sha256SlotList);
   790     pk11_InitSlotListStatic(&pk11_sha512SlotList);
   791     return SECSuccess;
   792 }
   794 void
   795 PK11_DestroySlotLists(void)
   796 {
   797     pk11_FreeSlotListStatic(&pk11_seedSlotList);
   798     pk11_FreeSlotListStatic(&pk11_camelliaSlotList);
   799     pk11_FreeSlotListStatic(&pk11_aesSlotList);
   800     pk11_FreeSlotListStatic(&pk11_desSlotList);
   801     pk11_FreeSlotListStatic(&pk11_rc4SlotList);
   802     pk11_FreeSlotListStatic(&pk11_rc2SlotList);
   803     pk11_FreeSlotListStatic(&pk11_rc5SlotList);
   804     pk11_FreeSlotListStatic(&pk11_md5SlotList);
   805     pk11_FreeSlotListStatic(&pk11_md2SlotList);
   806     pk11_FreeSlotListStatic(&pk11_sha1SlotList);
   807     pk11_FreeSlotListStatic(&pk11_rsaSlotList);
   808     pk11_FreeSlotListStatic(&pk11_dsaSlotList);
   809     pk11_FreeSlotListStatic(&pk11_dhSlotList);
   810     pk11_FreeSlotListStatic(&pk11_ecSlotList);
   811     pk11_FreeSlotListStatic(&pk11_ideaSlotList);
   812     pk11_FreeSlotListStatic(&pk11_sslSlotList);
   813     pk11_FreeSlotListStatic(&pk11_tlsSlotList);
   814     pk11_FreeSlotListStatic(&pk11_randomSlotList);
   815     pk11_FreeSlotListStatic(&pk11_sha256SlotList);
   816     pk11_FreeSlotListStatic(&pk11_sha512SlotList);
   817     return;
   818 }
   820 /* return a system slot list based on mechanism */
   821 PK11SlotList *
   822 PK11_GetSlotList(CK_MECHANISM_TYPE type)
   823 {
   824 /* XXX a workaround for Bugzilla bug #55267 */
   825 #if defined(HPUX) && defined(__LP64__)
   826     if (CKM_INVALID_MECHANISM == type)
   827         return NULL;
   828 #endif
   829     switch (type) {
   830     case CKM_SEED_CBC:
   831     case CKM_SEED_ECB:
   832 	return &pk11_seedSlotList;
   833     case CKM_CAMELLIA_CBC:
   834     case CKM_CAMELLIA_ECB:
   835 	return &pk11_camelliaSlotList;
   836     case CKM_AES_CBC:
   837     case CKM_AES_CCM:
   838     case CKM_AES_CTR:
   839     case CKM_AES_CTS:
   840     case CKM_AES_GCM:
   841     case CKM_AES_ECB:
   842 	return &pk11_aesSlotList;
   843     case CKM_DES_CBC:
   844     case CKM_DES_ECB:
   845     case CKM_DES3_ECB:
   846     case CKM_DES3_CBC:
   847 	return &pk11_desSlotList;
   848     case CKM_RC4:
   849 	return &pk11_rc4SlotList;
   850     case CKM_RC5_CBC:
   851 	return &pk11_rc5SlotList;
   852     case CKM_SHA_1:
   853 	return &pk11_sha1SlotList;
   854     case CKM_SHA224:
   855     case CKM_SHA256:
   856 	return &pk11_sha256SlotList;
   857     case CKM_SHA384:
   858     case CKM_SHA512:
   859 	return &pk11_sha512SlotList;
   860     case CKM_MD5:
   861 	return &pk11_md5SlotList;
   862     case CKM_MD2:
   863 	return &pk11_md2SlotList;
   864     case CKM_RC2_ECB:
   865     case CKM_RC2_CBC:
   866 	return &pk11_rc2SlotList;
   867     case CKM_RSA_PKCS:
   868     case CKM_RSA_PKCS_KEY_PAIR_GEN:
   869     case CKM_RSA_X_509:
   870 	return &pk11_rsaSlotList;
   871     case CKM_DSA:
   872 	return &pk11_dsaSlotList;
   873     case CKM_DH_PKCS_KEY_PAIR_GEN:
   874     case CKM_DH_PKCS_DERIVE:
   875 	return &pk11_dhSlotList;
   876     case CKM_ECDSA:
   877     case CKM_ECDSA_SHA1:
   878     case CKM_EC_KEY_PAIR_GEN: /* aka CKM_ECDSA_KEY_PAIR_GEN */
   879     case CKM_ECDH1_DERIVE:
   880 	return &pk11_ecSlotList;
   881     case CKM_SSL3_PRE_MASTER_KEY_GEN:
   882     case CKM_SSL3_MASTER_KEY_DERIVE:
   883     case CKM_SSL3_SHA1_MAC:
   884     case CKM_SSL3_MD5_MAC:
   885 	return &pk11_sslSlotList;
   886     case CKM_TLS_MASTER_KEY_DERIVE:
   887     case CKM_TLS_KEY_AND_MAC_DERIVE:
   888     case CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256:
   889 	return &pk11_tlsSlotList;
   890     case CKM_IDEA_CBC:
   891     case CKM_IDEA_ECB:
   892 	return &pk11_ideaSlotList;
   893     case CKM_FAKE_RANDOM:
   894 	return &pk11_randomSlotList;
   895     }
   896     return NULL;
   897 }
   899 /*
   900  * load the static SlotInfo structures used to select a PKCS11 slot.
   901  * preSlotInfo has a list of all the default flags for the slots on this
   902  * module.
   903  */
   904 void
   905 PK11_LoadSlotList(PK11SlotInfo *slot, PK11PreSlotInfo *psi, int count)
   906 {
   907     int i;
   909     for (i=0; i < count; i++) {
   910 	if (psi[i].slotID == slot->slotID)
   911 	    break;
   912     }
   914     if (i == count) return;
   916     slot->defaultFlags = psi[i].defaultFlags;
   917     slot->askpw = psi[i].askpw;
   918     slot->timeout = psi[i].timeout;
   919     slot->hasRootCerts = psi[i].hasRootCerts;
   921     /* if the slot is already disabled, don't load them into the
   922      * default slot lists. We get here so we can save the default
   923      * list value. */
   924     if (slot->disabled) return;
   926     /* if the user has disabled us, don't load us in */
   927     if (slot->defaultFlags & PK11_DISABLE_FLAG) {
   928 	slot->disabled = PR_TRUE;
   929 	slot->reason = PK11_DIS_USER_SELECTED;
   930 	/* free up sessions and things?? */
   931 	return;
   932     }
   934     for (i=0; i < num_pk11_default_mechanisms; i++) {
   935 	if (slot->defaultFlags & PK11_DefaultArray[i].flag) {
   936 	    CK_MECHANISM_TYPE mechanism = PK11_DefaultArray[i].mechanism;
   937 	    PK11SlotList *slotList = PK11_GetSlotList(mechanism);
   939 	    if (slotList) PK11_AddSlotToList(slotList,slot,PR_FALSE);
   940 	}
   941     }
   943     return;
   944 }
   947 /*
   948  * update a slot to its new attribute according to the slot list
   949  * returns: SECSuccess if nothing to do or add/delete is successful
   950  */
   951 SECStatus
   952 PK11_UpdateSlotAttribute(PK11SlotInfo *slot,
   953                          const PK11DefaultArrayEntry *entry,
   954                          PRBool add)
   955                          /* add: PR_TRUE if want to turn on */
   956 {
   957     SECStatus result = SECSuccess;
   958     PK11SlotList *slotList = PK11_GetSlotList(entry->mechanism);
   960     if (add) { /* trying to turn on a mechanism */
   962         /* turn on the default flag in the slot */
   963         slot->defaultFlags |= entry->flag;
   965         /* add this slot to the list */
   966         if (slotList!=NULL)
   967             result = PK11_AddSlotToList(slotList, slot, PR_FALSE);
   969     } else { /* trying to turn off */
   971         /* turn OFF the flag in the slot */ 
   972         slot->defaultFlags &= ~entry->flag;
   974         if (slotList) {
   975             /* find the element in the list & delete it */
   976             PK11SlotListElement *le = PK11_FindSlotElement(slotList, slot);
   978             /* remove the slot from the list */
   979             if (le)
   980                 result = PK11_DeleteSlotFromList(slotList, le);
   981         }
   982     }
   983     return result;
   984 }
   986 /*
   987  * clear a slot off of all of it's default list
   988  */
   989 void
   990 PK11_ClearSlotList(PK11SlotInfo *slot)
   991 {
   992     int i;
   994     if (slot->disabled) return;
   995     if (slot->defaultFlags == 0) return;
   997     for (i=0; i < num_pk11_default_mechanisms; i++) {
   998 	if (slot->defaultFlags & PK11_DefaultArray[i].flag) {
   999 	    CK_MECHANISM_TYPE mechanism = PK11_DefaultArray[i].mechanism;
  1000 	    PK11SlotList *slotList = PK11_GetSlotList(mechanism);
  1001 	    PK11SlotListElement *le = NULL;
  1003 	    if (slotList) le = PK11_FindSlotElement(slotList,slot);
  1005 	    if (le) {
  1006 		PK11_DeleteSlotFromList(slotList,le);
  1007 		PK11_FreeSlotListElement(slotList,le);
  1014 /******************************************************************
  1015  *           Slot initialization
  1016  ******************************************************************/
  1017 /*
  1018  * turn a PKCS11 Static Label into a string
  1019  */
  1020 char *
  1021 PK11_MakeString(PLArenaPool *arena,char *space,
  1022 					char *staticString,int stringLen)
  1024 	int i;
  1025 	char *newString;
  1026 	for(i=(stringLen-1); i >= 0; i--) {
  1027 	  if (staticString[i] != ' ') break;
  1029 	/* move i to point to the last space */
  1030 	i++;
  1031 	if (arena) {
  1032 	    newString = (char*)PORT_ArenaAlloc(arena,i+1 /* space for NULL */);
  1033 	} else if (space) {
  1034 	    newString = space;
  1035 	} else {
  1036 	    newString = (char*)PORT_Alloc(i+1 /* space for NULL */);
  1038 	if (newString == NULL) return NULL;
  1040 	if (i) PORT_Memcpy(newString,staticString, i);
  1041 	newString[i] = 0;
  1043 	return newString;
  1046 /*
  1047  * Reads in the slots mechanism list for later use
  1048  */
  1049 SECStatus
  1050 PK11_ReadMechanismList(PK11SlotInfo *slot)
  1052     CK_ULONG count;
  1053     CK_RV crv;
  1054     PRUint32 i;
  1056     if (slot->mechanismList) {
  1057 	PORT_Free(slot->mechanismList);
  1058 	slot->mechanismList = NULL;
  1060     slot->mechanismCount = 0;
  1062     if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1063     crv = PK11_GETTAB(slot)->C_GetMechanismList(slot->slotID,NULL,&count);
  1064     if (crv != CKR_OK) {
  1065 	if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1066 	PORT_SetError(PK11_MapError(crv));
  1067 	return SECFailure;
  1070     slot->mechanismList = (CK_MECHANISM_TYPE *)
  1071 			    PORT_Alloc(count *sizeof(CK_MECHANISM_TYPE));
  1072     if (slot->mechanismList == NULL) {
  1073 	if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1074 	return SECFailure;
  1076     crv = PK11_GETTAB(slot)->C_GetMechanismList(slot->slotID,
  1077 						slot->mechanismList, &count);
  1078     if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1079     if (crv != CKR_OK) {
  1080 	PORT_Free(slot->mechanismList);
  1081 	slot->mechanismList = NULL;
  1082 	PORT_SetError(PK11_MapError(crv));
  1083 	return SECSuccess;
  1085     slot->mechanismCount = count;
  1086     PORT_Memset(slot->mechanismBits, 0, sizeof(slot->mechanismBits));
  1088     for (i=0; i < count; i++) {
  1089 	CK_MECHANISM_TYPE mech = slot->mechanismList[i];
  1090 	if (mech < 0x7ff) {
  1091 	    slot->mechanismBits[mech & 0xff] |= 1 << (mech >> 8);
  1094     return SECSuccess;
  1097 /*
  1098  * initialize a new token
  1099  * unlike initialize slot, this can be called multiple times in the lifetime
  1100  * of NSS. It reads the information associated with a card or token,
  1101  * that is not going to change unless the card or token changes.
  1102  */
  1103 SECStatus
  1104 PK11_InitToken(PK11SlotInfo *slot, PRBool loadCerts)
  1106     CK_TOKEN_INFO tokenInfo;
  1107     CK_RV crv;
  1108     char *tmp;
  1109     SECStatus rv;
  1110     PRStatus status;
  1112     /* set the slot flags to the current token values */
  1113     if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1114     crv = PK11_GETTAB(slot)->C_GetTokenInfo(slot->slotID,&tokenInfo);
  1115     if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1116     if (crv != CKR_OK) {
  1117 	PORT_SetError(PK11_MapError(crv));
  1118 	return SECFailure;
  1121     /* set the slot flags to the current token values */
  1122     slot->series++; /* allow other objects to detect that the 
  1123 		      * slot is different */
  1124     slot->flags = tokenInfo.flags;
  1125     slot->needLogin = ((tokenInfo.flags & CKF_LOGIN_REQUIRED) ? 
  1126 							PR_TRUE : PR_FALSE);
  1127     slot->readOnly = ((tokenInfo.flags & CKF_WRITE_PROTECTED) ? 
  1128 							PR_TRUE : PR_FALSE);
  1131     slot->hasRandom = ((tokenInfo.flags & CKF_RNG) ? PR_TRUE : PR_FALSE);
  1132     slot->protectedAuthPath =
  1133     		((tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) 
  1134 	 						? PR_TRUE : PR_FALSE);
  1135     slot->lastLoginCheck = 0;
  1136     slot->lastState = 0;
  1137     /* on some platforms Active Card incorrectly sets the 
  1138      * CKF_PROTECTED_AUTHENTICATION_PATH bit when it doesn't mean to. */
  1139     if (slot->isActiveCard) {
  1140 	slot->protectedAuthPath = PR_FALSE;
  1142     tmp = PK11_MakeString(NULL,slot->token_name,
  1143 			(char *)tokenInfo.label, sizeof(tokenInfo.label));
  1144     slot->minPassword = tokenInfo.ulMinPinLen;
  1145     slot->maxPassword = tokenInfo.ulMaxPinLen;
  1146     PORT_Memcpy(slot->serial,tokenInfo.serialNumber,sizeof(slot->serial));
  1148     nssToken_UpdateName(slot->nssToken);
  1150     slot->defRWSession = (PRBool)((!slot->readOnly) && 
  1151 					(tokenInfo.ulMaxSessionCount == 1));
  1152     rv = PK11_ReadMechanismList(slot);
  1153     if (rv != SECSuccess) return rv;
  1155     slot->hasRSAInfo = PR_FALSE;
  1156     slot->RSAInfoFlags = 0;
  1158     /* initialize the maxKeyCount value */
  1159     if (tokenInfo.ulMaxSessionCount == 0) {
  1160 	slot->maxKeyCount = 800; /* should be #define or a config param */
  1161     } else if (tokenInfo.ulMaxSessionCount < 20) {
  1162 	/* don't have enough sessions to keep that many keys around */
  1163 	slot->maxKeyCount = 0;
  1164     } else {
  1165 	slot->maxKeyCount = tokenInfo.ulMaxSessionCount/2;
  1168     /* Make sure our session handle is valid */
  1169     if (slot->session == CK_INVALID_SESSION) {
  1170 	/* we know we don't have a valid session, go get one */
  1171 	CK_SESSION_HANDLE session;
  1173 	/* session should be Readonly, serial */
  1174 	if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1175 	crv = PK11_GETTAB(slot)->C_OpenSession(slot->slotID,
  1176 	      (slot->defRWSession ? CKF_RW_SESSION : 0) | CKF_SERIAL_SESSION,
  1177 				  slot,pk11_notify,&session);
  1178 	if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1179 	if (crv != CKR_OK) {
  1180 	    PORT_SetError(PK11_MapError(crv));
  1181 	    return SECFailure;
  1183 	slot->session = session;
  1184     } else {
  1185 	/* The session we have may be defunct (the token associated with it)
  1186 	 * has been removed   */
  1187 	CK_SESSION_INFO sessionInfo;
  1189 	if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1190 	crv = PK11_GETTAB(slot)->C_GetSessionInfo(slot->session,&sessionInfo);
  1191         if (crv == CKR_DEVICE_ERROR) {
  1192 	    PK11_GETTAB(slot)->C_CloseSession(slot->session);
  1193 	    crv = CKR_SESSION_CLOSED;
  1195 	if ((crv==CKR_SESSION_CLOSED) || (crv==CKR_SESSION_HANDLE_INVALID)) {
  1196 	    crv =PK11_GETTAB(slot)->C_OpenSession(slot->slotID,
  1197 	      (slot->defRWSession ? CKF_RW_SESSION : 0) | CKF_SERIAL_SESSION,
  1198 					slot,pk11_notify,&slot->session);
  1199 	    if (crv != CKR_OK) {
  1200 	        PORT_SetError(PK11_MapError(crv));
  1201 		slot->session = CK_INVALID_SESSION;
  1202 		if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1203 		return SECFailure;
  1206 	if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1209     status = nssToken_Refresh(slot->nssToken);
  1210     if (status != PR_SUCCESS)
  1211     	return SECFailure;
  1213     if (!(slot->isInternal) && (slot->hasRandom)) {
  1214 	/* if this slot has a random number generater, use it to add entropy
  1215 	 * to the internal slot. */
  1216 	PK11SlotInfo *int_slot = PK11_GetInternalSlot();
  1218 	if (int_slot) {
  1219 	    unsigned char random_bytes[32];
  1221 	    /* if this slot can issue random numbers, get some entropy from
  1222 	     * that random number generater and give it to our internal token.
  1223 	     */
  1224 	    PK11_EnterSlotMonitor(slot);
  1225 	    crv = PK11_GETTAB(slot)->C_GenerateRandom
  1226 			(slot->session,random_bytes, sizeof(random_bytes));
  1227 	    PK11_ExitSlotMonitor(slot);
  1228 	    if (crv == CKR_OK) {
  1229 	        PK11_EnterSlotMonitor(int_slot);
  1230 		PK11_GETTAB(int_slot)->C_SeedRandom(int_slot->session,
  1231 					random_bytes, sizeof(random_bytes));
  1232 	        PK11_ExitSlotMonitor(int_slot);
  1235 	    /* Now return the favor and send entropy to the token's random 
  1236 	     * number generater */
  1237 	    PK11_EnterSlotMonitor(int_slot);
  1238 	    crv = PK11_GETTAB(int_slot)->C_GenerateRandom(int_slot->session,
  1239 					random_bytes, sizeof(random_bytes));
  1240 	    PK11_ExitSlotMonitor(int_slot);
  1241 	    if (crv == CKR_OK) {
  1242 	        PK11_EnterSlotMonitor(slot);
  1243 		crv = PK11_GETTAB(slot)->C_SeedRandom(slot->session,
  1244 					random_bytes, sizeof(random_bytes));
  1245 	        PK11_ExitSlotMonitor(slot);
  1247 	    PK11_FreeSlot(int_slot);
  1250     /* work around a problem in softoken where it incorrectly
  1251      * reports databases opened read only as read/write. */
  1252     if (slot->isInternal && !slot->readOnly) {
  1253 	CK_SESSION_HANDLE session = CK_INVALID_SESSION;
  1255 	/* try to open a R/W session */
  1256 	crv =PK11_GETTAB(slot)->C_OpenSession(slot->slotID,
  1257 	      CKF_RW_SESSION|CKF_SERIAL_SESSION, slot, pk11_notify ,&session);
  1258 	/* what a well behaved token should return if you open 
  1259 	 * a RW session on a read only token */
  1260 	if (crv == CKR_TOKEN_WRITE_PROTECTED) {
  1261 	    slot->readOnly = PR_TRUE;
  1262 	} else if (crv == CKR_OK) {
  1263 	    CK_SESSION_INFO sessionInfo;
  1265 	    /* Because of a second bug in softoken, which silently returns
  1266 	     * a RO session, we need to check what type of session we got. */
  1267 	    crv = PK11_GETTAB(slot)->C_GetSessionInfo(session, &sessionInfo);
  1268 	    if (crv == CKR_OK) {
  1269 		if ((sessionInfo.flags & CKF_RW_SESSION) == 0) {
  1270 		    /* session was readonly, so this softoken slot must be 			     * readonly */
  1271 		    slot->readOnly = PR_TRUE;
  1274 	    PK11_GETTAB(slot)->C_CloseSession(session);
  1278     return SECSuccess;
  1281 /*
  1282  * initialize a new token
  1283  * unlike initialize slot, this can be called multiple times in the lifetime
  1284  * of NSS. It reads the information associated with a card or token,
  1285  * that is not going to change unless the card or token changes.
  1286  */
  1287 SECStatus
  1288 PK11_TokenRefresh(PK11SlotInfo *slot)
  1290     CK_TOKEN_INFO tokenInfo;
  1291     CK_RV crv;
  1293     /* set the slot flags to the current token values */
  1294     if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1295     crv = PK11_GETTAB(slot)->C_GetTokenInfo(slot->slotID,&tokenInfo);
  1296     if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1297     if (crv != CKR_OK) {
  1298 	PORT_SetError(PK11_MapError(crv));
  1299 	return SECFailure;
  1302     slot->flags = tokenInfo.flags;
  1303     slot->needLogin = ((tokenInfo.flags & CKF_LOGIN_REQUIRED) ? 
  1304 							PR_TRUE : PR_FALSE);
  1305     slot->readOnly = ((tokenInfo.flags & CKF_WRITE_PROTECTED) ? 
  1306 							PR_TRUE : PR_FALSE);
  1307     slot->hasRandom = ((tokenInfo.flags & CKF_RNG) ? PR_TRUE : PR_FALSE);
  1308     slot->protectedAuthPath =
  1309     		((tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) 
  1310 	 						? PR_TRUE : PR_FALSE);
  1311     /* on some platforms Active Card incorrectly sets the 
  1312      * CKF_PROTECTED_AUTHENTICATION_PATH bit when it doesn't mean to. */
  1313     if (slot->isActiveCard) {
  1314 	slot->protectedAuthPath = PR_FALSE;
  1316     return SECSuccess;
  1319 static PRBool
  1320 pk11_isRootSlot(PK11SlotInfo *slot) 
  1322     CK_ATTRIBUTE findTemp[1];
  1323     CK_ATTRIBUTE *attrs;
  1324     CK_OBJECT_CLASS oclass = CKO_NETSCAPE_BUILTIN_ROOT_LIST;
  1325     int tsize;
  1326     CK_OBJECT_HANDLE handle;
  1328     attrs = findTemp;
  1329     PK11_SETATTRS(attrs, CKA_CLASS, &oclass, sizeof(oclass)); attrs++;
  1330     tsize = attrs - findTemp;
  1331     PORT_Assert(tsize <= sizeof(findTemp)/sizeof(CK_ATTRIBUTE));
  1333     handle = pk11_FindObjectByTemplate(slot,findTemp,tsize);
  1334     if (handle == CK_INVALID_HANDLE) {
  1335 	return PR_FALSE;
  1337     return PR_TRUE;
  1340 /*
  1341  * Initialize the slot :
  1342  * This initialization code is called on each slot a module supports when
  1343  * it is loaded. It does the bringup initialization. The difference between
  1344  * this and InitToken is Init slot does those one time initialization stuff,
  1345  * usually associated with the reader, while InitToken may get called multiple
  1346  * times as tokens are removed and re-inserted.
  1347  */
  1348 void
  1349 PK11_InitSlot(SECMODModule *mod, CK_SLOT_ID slotID, PK11SlotInfo *slot)
  1351     SECStatus rv;
  1352     char *tmp;
  1353     CK_SLOT_INFO slotInfo;
  1355     slot->functionList = mod->functionList;
  1356     slot->isInternal = mod->internal;
  1357     slot->slotID = slotID;
  1358     slot->isThreadSafe = mod->isThreadSafe;
  1359     slot->hasRSAInfo = PR_FALSE;
  1361     if (PK11_GETTAB(slot)->C_GetSlotInfo(slotID,&slotInfo) != CKR_OK) {
  1362 	slot->disabled = PR_TRUE;
  1363 	slot->reason = PK11_DIS_COULD_NOT_INIT_TOKEN;
  1364 	return;
  1367     /* test to make sure claimed mechanism work */
  1368     slot->needTest = mod->internal ? PR_FALSE : PR_TRUE;
  1369     slot->module = mod; /* NOTE: we don't make a reference here because
  1370 			 * modules have references to their slots. This
  1371 			 * works because modules keep implicit references
  1372 			 * from their slots, and won't unload and disappear
  1373 			 * until all their slots have been freed */
  1374     tmp = PK11_MakeString(NULL,slot->slot_name,
  1375 	 (char *)slotInfo.slotDescription, sizeof(slotInfo.slotDescription));
  1376     slot->isHW = (PRBool)((slotInfo.flags & CKF_HW_SLOT) == CKF_HW_SLOT);
  1377 #define ACTIVE_CARD "ActivCard SA"
  1378     slot->isActiveCard = (PRBool)(PORT_Strncmp((char *)slotInfo.manufacturerID,
  1379 				ACTIVE_CARD, sizeof(ACTIVE_CARD)-1) == 0);
  1380     if ((slotInfo.flags & CKF_REMOVABLE_DEVICE) == 0) {
  1381 	slot->isPerm = PR_TRUE;
  1382 	/* permanment slots must have the token present always */
  1383 	if ((slotInfo.flags & CKF_TOKEN_PRESENT) == 0) {
  1384 	    slot->disabled = PR_TRUE;
  1385 	    slot->reason = PK11_DIS_TOKEN_NOT_PRESENT;
  1386 	    return; /* nothing else to do */
  1389     /* if the token is present, initialize it */
  1390     if ((slotInfo.flags & CKF_TOKEN_PRESENT) != 0) {
  1391 	rv = PK11_InitToken(slot,PR_TRUE);
  1392 	/* the only hard failures are on permanent devices, or function
  1393 	 * verify failures... function verify failures are already handled
  1394 	 * by tokenInit */
  1395 	if ((rv != SECSuccess) && (slot->isPerm) && (!slot->disabled)) {
  1396 	    slot->disabled = PR_TRUE;
  1397 	    slot->reason = PK11_DIS_COULD_NOT_INIT_TOKEN;
  1399 	if (rv == SECSuccess && pk11_isRootSlot(slot)) {
  1400 	    if (!slot->hasRootCerts) {
  1401 		slot->module->trustOrder = 100;
  1403 	    slot->hasRootCerts= PR_TRUE;
  1410 /*********************************************************************
  1411  *            Slot mapping utility functions.
  1412  *********************************************************************/
  1414 /*
  1415  * determine if the token is present. If the token is present, make sure
  1416  * we have a valid session handle. Also set the value of needLogin 
  1417  * appropriately.
  1418  */
  1419 static PRBool
  1420 pk11_IsPresentCertLoad(PK11SlotInfo *slot, PRBool loadCerts)
  1422     CK_SLOT_INFO slotInfo;
  1423     CK_SESSION_INFO sessionInfo;
  1424     CK_RV crv;
  1426     /* disabled slots are never present */
  1427     if (slot->disabled) {
  1428 	return PR_FALSE;
  1431     /* permanent slots are always present */
  1432     if (slot->isPerm && (slot->session != CK_INVALID_SESSION)) {
  1433 	return PR_TRUE;
  1436     if (slot->nssToken) {
  1437 	return nssToken_IsPresent(slot->nssToken);
  1440     /* removable slots have a flag that says they are present */
  1441     if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1442     if (PK11_GETTAB(slot)->C_GetSlotInfo(slot->slotID,&slotInfo) != CKR_OK) {
  1443         if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1444 	return PR_FALSE;
  1446     if ((slotInfo.flags & CKF_TOKEN_PRESENT) == 0) {
  1447 	/* if the slot is no longer present, close the session */
  1448 	if (slot->session != CK_INVALID_SESSION) {
  1449 	    PK11_GETTAB(slot)->C_CloseSession(slot->session);
  1450 	    slot->session = CK_INVALID_SESSION;
  1452         if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1453 	return PR_FALSE;
  1456     /* use the session Info to determine if the card has been removed and then
  1457      * re-inserted */
  1458     if (slot->session != CK_INVALID_SESSION) {
  1459 	if (slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1460 	crv = PK11_GETTAB(slot)->C_GetSessionInfo(slot->session, &sessionInfo);
  1461 	if (crv != CKR_OK) {
  1462 	    PK11_GETTAB(slot)->C_CloseSession(slot->session);
  1463 	    slot->session = CK_INVALID_SESSION;
  1465         if (slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1467     if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1469     /* card has not been removed, current token info is correct */
  1470     if (slot->session != CK_INVALID_SESSION) return PR_TRUE;
  1472     /* initialize the token info state */
  1473     if (PK11_InitToken(slot,loadCerts) != SECSuccess) {
  1474 	return PR_FALSE;
  1477     return PR_TRUE;
  1480 /*
  1481  * old version of the routine
  1482  */
  1483 PRBool
  1484 PK11_IsPresent(PK11SlotInfo *slot) {
  1485    return pk11_IsPresentCertLoad(slot,PR_TRUE);
  1488 /* is the slot disabled? */
  1489 PRBool
  1490 PK11_IsDisabled(PK11SlotInfo *slot)
  1492     return slot->disabled;
  1495 /* and why? */
  1496 PK11DisableReasons
  1497 PK11_GetDisabledReason(PK11SlotInfo *slot)
  1499     return slot->reason;
  1502 /* returns PR_TRUE if successfully disable the slot */
  1503 /* returns PR_FALSE otherwise */
  1504 PRBool PK11_UserDisableSlot(PK11SlotInfo *slot) {
  1506     /* Prevent users from disabling the internal module. */
  1507     if (slot->isInternal) {
  1508 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1509 	return PR_FALSE;
  1512     slot->defaultFlags |= PK11_DISABLE_FLAG;
  1513     slot->disabled = PR_TRUE;
  1514     slot->reason = PK11_DIS_USER_SELECTED;
  1516     return PR_TRUE;
  1519 PRBool PK11_UserEnableSlot(PK11SlotInfo *slot) {
  1521     slot->defaultFlags &= ~PK11_DISABLE_FLAG;
  1522     slot->disabled = PR_FALSE;
  1523     slot->reason = PK11_DIS_NONE;
  1524     return PR_TRUE;
  1527 PRBool PK11_HasRootCerts(PK11SlotInfo *slot) {
  1528     return slot->hasRootCerts;
  1531 /* Get the module this slot is attached to */
  1532 SECMODModule *
  1533 PK11_GetModule(PK11SlotInfo *slot)
  1535 	return slot->module;
  1538 /* return the default flags of a slot */
  1539 unsigned long
  1540 PK11_GetDefaultFlags(PK11SlotInfo *slot)
  1542 	return slot->defaultFlags;
  1545 /*
  1546  * The following wrapper functions allow us to export an opaque slot
  1547  * function to the rest of libsec and the world... */
  1548 PRBool
  1549 PK11_IsReadOnly(PK11SlotInfo *slot)
  1551     return slot->readOnly;
  1554 PRBool
  1555 PK11_IsHW(PK11SlotInfo *slot)
  1557     return slot->isHW;
  1560 PRBool
  1561 PK11_IsRemovable(PK11SlotInfo *slot)
  1563     return !slot->isPerm;
  1566 PRBool
  1567 PK11_IsInternal(PK11SlotInfo *slot)
  1569     return slot->isInternal;
  1572 PRBool
  1573 PK11_IsInternalKeySlot(PK11SlotInfo *slot)
  1575     PK11SlotInfo *int_slot;
  1576     PRBool result;
  1578     if (!slot->isInternal) {
  1579 	return PR_FALSE;
  1582     int_slot = PK11_GetInternalKeySlot();
  1583     result = (int_slot == slot) ? PR_TRUE : PR_FALSE;
  1584     PK11_FreeSlot(int_slot);
  1585     return result;
  1588 PRBool
  1589 PK11_NeedLogin(PK11SlotInfo *slot)
  1591     return slot->needLogin;
  1594 PRBool
  1595 PK11_IsFriendly(PK11SlotInfo *slot)
  1597     /* internal slot always has public readable certs */
  1598     return (PRBool)(slot->isInternal || 
  1599 		    ((slot->defaultFlags & SECMOD_FRIENDLY_FLAG) == 
  1600 		     SECMOD_FRIENDLY_FLAG));
  1603 char *
  1604 PK11_GetTokenName(PK11SlotInfo *slot)
  1606      return slot->token_name;
  1609 char *
  1610 PK11_GetSlotName(PK11SlotInfo *slot)
  1612      return slot->slot_name;
  1615 int
  1616 PK11_GetSlotSeries(PK11SlotInfo *slot)
  1618     return slot->series;
  1621 int
  1622 PK11_GetCurrentWrapIndex(PK11SlotInfo *slot)
  1624     return slot->wrapKey;
  1627 CK_SLOT_ID
  1628 PK11_GetSlotID(PK11SlotInfo *slot)
  1630     return slot->slotID;
  1633 SECMODModuleID
  1634 PK11_GetModuleID(PK11SlotInfo *slot)
  1636     return slot->module->moduleID;
  1639 static void
  1640 pk11_zeroTerminatedToBlankPadded(CK_CHAR *buffer, size_t buffer_size)
  1642     CK_CHAR *walk = buffer;
  1643     CK_CHAR *end = buffer + buffer_size;
  1645     /* find the NULL */
  1646     while (walk < end && *walk != '\0') {
  1647 	walk++;
  1650     /* clear out the buffer */
  1651     while (walk < end) {
  1652 	*walk++ = ' ';
  1656 /* return the slot info structure */
  1657 SECStatus
  1658 PK11_GetSlotInfo(PK11SlotInfo *slot, CK_SLOT_INFO *info)
  1660     CK_RV crv;
  1662     if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1663     /*
  1664      * some buggy drivers do not fill the buffer completely, 
  1665      * erase the buffer first
  1666      */
  1667     PORT_Memset(info->slotDescription,' ',sizeof(info->slotDescription));
  1668     PORT_Memset(info->manufacturerID,' ',sizeof(info->manufacturerID));
  1669     crv = PK11_GETTAB(slot)->C_GetSlotInfo(slot->slotID,info);
  1670     pk11_zeroTerminatedToBlankPadded(info->slotDescription,
  1671 					sizeof(info->slotDescription));
  1672     pk11_zeroTerminatedToBlankPadded(info->manufacturerID,
  1673 					sizeof(info->manufacturerID));
  1674     if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1675     if (crv != CKR_OK) {
  1676 	PORT_SetError(PK11_MapError(crv));
  1677 	return SECFailure;
  1679     return SECSuccess;
  1682 /*  return the token info structure */
  1683 SECStatus
  1684 PK11_GetTokenInfo(PK11SlotInfo *slot, CK_TOKEN_INFO *info)
  1686     CK_RV crv;
  1687     if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  1688     /*
  1689      * some buggy drivers do not fill the buffer completely, 
  1690      * erase the buffer first
  1691      */
  1692     PORT_Memset(info->label,' ',sizeof(info->label));
  1693     PORT_Memset(info->manufacturerID,' ',sizeof(info->manufacturerID));
  1694     PORT_Memset(info->model,' ',sizeof(info->model));
  1695     PORT_Memset(info->serialNumber,' ',sizeof(info->serialNumber));
  1696     crv = PK11_GETTAB(slot)->C_GetTokenInfo(slot->slotID,info);
  1697     pk11_zeroTerminatedToBlankPadded(info->label,sizeof(info->label));
  1698     pk11_zeroTerminatedToBlankPadded(info->manufacturerID,
  1699 					sizeof(info->manufacturerID));
  1700     pk11_zeroTerminatedToBlankPadded(info->model,sizeof(info->model));
  1701     pk11_zeroTerminatedToBlankPadded(info->serialNumber,
  1702 					sizeof(info->serialNumber));
  1703     if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  1704     if (crv != CKR_OK) {
  1705 	PORT_SetError(PK11_MapError(crv));
  1706 	return SECFailure;
  1708     return SECSuccess;
  1711 /* Find out if we need to initialize the user's pin */
  1712 PRBool
  1713 PK11_NeedUserInit(PK11SlotInfo *slot)
  1715     PRBool needUserInit = (PRBool) ((slot->flags & CKF_USER_PIN_INITIALIZED) 
  1716 					== 0);
  1718     if (needUserInit) {
  1719 	CK_TOKEN_INFO info;
  1720 	SECStatus rv;
  1722 	/* see if token has been initialized off line */
  1723 	rv = PK11_GetTokenInfo(slot, &info);
  1724 	if (rv == SECSuccess) {
  1725 	    slot->flags = info.flags;
  1728     return (PRBool)((slot->flags & CKF_USER_PIN_INITIALIZED) == 0);
  1731 static PK11SlotInfo *pk11InternalKeySlot = NULL;
  1733 /*
  1734  * Set a new default internal keyslot. If one has already been set, clear it.
  1735  * Passing NULL falls back to the NSS normally selected default internal key
  1736  * slot.
  1737  */
  1738 void
  1739 pk11_SetInternalKeySlot(PK11SlotInfo *slot)
  1741    if (pk11InternalKeySlot) {
  1742 	PK11_FreeSlot(pk11InternalKeySlot);
  1744    pk11InternalKeySlot = slot ? PK11_ReferenceSlot(slot) : NULL;
  1747 /*
  1748  * Set a new default internal keyslot if the normal key slot has not already
  1749  * been overridden. Subsequent calls to this function will be ignored unless
  1750  * pk11_SetInternalKeySlot is used to clear the current default.
  1751  */
  1752 void
  1753 pk11_SetInternalKeySlotIfFirst(PK11SlotInfo *slot)
  1755    if (pk11InternalKeySlot) {
  1756 	return;
  1758    pk11InternalKeySlot = slot ? PK11_ReferenceSlot(slot) : NULL;
  1761 /*
  1762  * Swap out a default internal keyslot.  Caller owns the Slot Reference
  1763  */
  1764 PK11SlotInfo *
  1765 pk11_SwapInternalKeySlot(PK11SlotInfo *slot)
  1767    PK11SlotInfo *swap = pk11InternalKeySlot;
  1769    pk11InternalKeySlot = slot ? PK11_ReferenceSlot(slot) : NULL;
  1770    return swap;
  1774 /* get the internal key slot. FIPS has only one slot for both key slots and
  1775  * default slots */
  1776 PK11SlotInfo *
  1777 PK11_GetInternalKeySlot(void)
  1779     SECMODModule *mod;
  1781     if (pk11InternalKeySlot) {
  1782 	return PK11_ReferenceSlot(pk11InternalKeySlot);
  1785     mod = SECMOD_GetInternalModule();
  1786     PORT_Assert(mod != NULL);
  1787     if (!mod) {
  1788 	PORT_SetError( SEC_ERROR_NO_MODULE );
  1789 	return NULL;
  1791     return PK11_ReferenceSlot(mod->isFIPS ? mod->slots[0] : mod->slots[1]);
  1794 /* get the internal default slot */
  1795 PK11SlotInfo *
  1796 PK11_GetInternalSlot(void) 
  1798     SECMODModule * mod = SECMOD_GetInternalModule();
  1799     PORT_Assert(mod != NULL);
  1800     if (!mod) {
  1801 	PORT_SetError( SEC_ERROR_NO_MODULE );
  1802 	return NULL;
  1804     if (mod->isFIPS) {
  1805 	return PK11_GetInternalKeySlot();
  1807     return PK11_ReferenceSlot(mod->slots[0]);
  1810 /*
  1811  * check if a given slot supports the requested mechanism
  1812  */
  1813 PRBool
  1814 PK11_DoesMechanism(PK11SlotInfo *slot, CK_MECHANISM_TYPE type)
  1816     int i;
  1818     /* CKM_FAKE_RANDOM is not a real PKCS mechanism. It's a marker to
  1819      * tell us we're looking form someone that has implemented get
  1820      * random bits */
  1821     if (type == CKM_FAKE_RANDOM) {
  1822 	return slot->hasRandom;
  1825     /* for most mechanism, bypass the linear lookup */
  1826     if (type < 0x7ff) {
  1827 	return (slot->mechanismBits[type & 0xff] & (1 << (type >> 8)))  ?
  1828 		PR_TRUE : PR_FALSE;
  1831     for (i=0; i < (int) slot->mechanismCount; i++) {
  1832 	if (slot->mechanismList[i] == type) return PR_TRUE;
  1834     return PR_FALSE;
  1837 /*
  1838  * Return true if a token that can do the desired mechanism exists.
  1839  * This allows us to have hardware tokens that can do function XYZ magically
  1840  * allow SSL Ciphers to appear if they are plugged in.
  1841  */
  1842 PRBool
  1843 PK11_TokenExists(CK_MECHANISM_TYPE type)
  1845     SECMODModuleList *mlp;
  1846     SECMODModuleList *modules;
  1847     SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
  1848     PK11SlotInfo *slot;
  1849     PRBool found = PR_FALSE;
  1850     int i;
  1852     if (!moduleLock) {
  1853     	PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
  1854 	return found;
  1856     /* we only need to know if there is a token that does this mechanism.
  1857      * check the internal module first because it's fast, and supports 
  1858      * almost everything. */
  1859     slot = PK11_GetInternalSlot();
  1860     if (slot) {
  1861     	found = PK11_DoesMechanism(slot,type);
  1862 	PK11_FreeSlot(slot);
  1864     if (found) return PR_TRUE; /* bypass getting module locks */
  1866     SECMOD_GetReadLock(moduleLock);
  1867     modules = SECMOD_GetDefaultModuleList();
  1868     for(mlp = modules; mlp != NULL && (!found); mlp = mlp->next) {
  1869 	for (i=0; i < mlp->module->slotCount; i++) {
  1870 	    slot = mlp->module->slots[i];
  1871 	    if (PK11_IsPresent(slot)) {
  1872 		if (PK11_DoesMechanism(slot,type)) {
  1873 		    found = PR_TRUE;
  1874 		    break;
  1879     SECMOD_ReleaseReadLock(moduleLock);
  1880     return found;
  1883 /*
  1884  * get all the currently available tokens in a list.
  1885  * that can perform the given mechanism. If mechanism is CKM_INVALID_MECHANISM,
  1886  * get all the tokens. Make sure tokens that need authentication are put at
  1887  * the end of this list.
  1888  */
  1889 PK11SlotList *
  1890 PK11_GetAllTokens(CK_MECHANISM_TYPE type, PRBool needRW, PRBool loadCerts, 
  1891                   void *wincx)
  1893     PK11SlotList *     list;
  1894     PK11SlotList *     loginList;
  1895     PK11SlotList *     friendlyList;
  1896     SECMODModuleList * mlp;
  1897     SECMODModuleList * modules;
  1898     SECMODListLock *   moduleLock;
  1899     int                i;
  1900 #if defined( XP_WIN32 ) 
  1901     int                j            = 0;
  1902     PRInt32            waste[16];
  1903 #endif
  1905     moduleLock   = SECMOD_GetDefaultModuleListLock();
  1906     if (!moduleLock) {
  1907     	PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
  1908 	return NULL;
  1911     list         = PK11_NewSlotList();
  1912     loginList    = PK11_NewSlotList();
  1913     friendlyList = PK11_NewSlotList();
  1914     if ((list == NULL)  || (loginList == NULL) || (friendlyList == NULL)) {
  1915 	if (list) PK11_FreeSlotList(list);
  1916 	if (loginList) PK11_FreeSlotList(loginList);
  1917 	if (friendlyList) PK11_FreeSlotList(friendlyList);
  1918 	return NULL;
  1921     SECMOD_GetReadLock(moduleLock);
  1923     modules      = SECMOD_GetDefaultModuleList();
  1924     for(mlp = modules; mlp != NULL; mlp = mlp->next) {
  1926 #if defined( XP_WIN32 ) 
  1927 	/* This is works around some horrible cache/page thrashing problems 
  1928 	** on Win32.  Without this, this loop can take up to 6 seconds at 
  1929 	** 100% CPU on a Pentium-Pro 200.  The thing this changes is to 
  1930 	** increase the size of the stack frame and modify it.  
  1931 	** Moving the loop code itself seems to have no effect.
  1932 	** Dunno why this combination makes a difference, but it does.
  1933 	*/
  1934 	waste[ j & 0xf] = j++; 
  1935 #endif
  1937 	for (i = 0; i < mlp->module->slotCount; i++) {
  1938 	    PK11SlotInfo *slot = mlp->module->slots[i];
  1940 	    if (pk11_IsPresentCertLoad(slot, loadCerts)) {
  1941 		if (needRW &&  slot->readOnly) continue;
  1942 		if ((type == CKM_INVALID_MECHANISM) 
  1943 					|| PK11_DoesMechanism(slot, type)) {
  1944 		    if (pk11_LoginStillRequired(slot,wincx)) {
  1945 			if (PK11_IsFriendly(slot)) {
  1946 			    PK11_AddSlotToList(friendlyList, slot, PR_TRUE);
  1947 			} else {
  1948 			    PK11_AddSlotToList(loginList, slot, PR_TRUE);
  1950 		    } else {
  1951 			PK11_AddSlotToList(list, slot, PR_TRUE);
  1957     SECMOD_ReleaseReadLock(moduleLock);
  1959     pk11_MoveListToList(list,friendlyList);
  1960     PK11_FreeSlotList(friendlyList);
  1961     pk11_MoveListToList(list,loginList);
  1962     PK11_FreeSlotList(loginList);
  1964     return list;
  1967 /*
  1968  * NOTE: This routine is working from a private List generated by 
  1969  * PK11_GetAllTokens. That is why it does not need to lock.
  1970  */
  1971 PK11SlotList *
  1972 PK11_GetPrivateKeyTokens(CK_MECHANISM_TYPE type,PRBool needRW,void *wincx)
  1974     PK11SlotList *list = PK11_GetAllTokens(type,needRW,PR_TRUE,wincx);
  1975     PK11SlotListElement *le, *next ;
  1976     SECStatus rv;
  1978     if (list == NULL) return list;
  1980     for (le = list->head ; le; le = next) {
  1981 	next = le->next; /* save the pointer here in case we have to 
  1982 			  * free the element later */
  1983         rv = PK11_Authenticate(le->slot,PR_TRUE,wincx);
  1984 	if (rv != SECSuccess) {
  1985 	    PK11_DeleteSlotFromList(list,le);
  1986 	    continue;
  1989     return list;
  1992 /*
  1993  * returns true if the slot doesn't conform to the requested attributes
  1994  */
  1995 PRBool
  1996 pk11_filterSlot(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, 
  1997 	CK_FLAGS mechanismInfoFlags, unsigned int keySize) 
  1999     CK_MECHANISM_INFO mechanism_info;
  2000     CK_RV crv = CKR_OK;
  2002     /* handle the only case where we don't actually fetch the mechanisms
  2003      * on the fly */
  2004     if ((keySize == 0) && (mechanism == CKM_RSA_PKCS) && (slot->hasRSAInfo)) {
  2005 	mechanism_info.flags = slot->RSAInfoFlags;
  2006     } else {
  2007 	if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  2008     	crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID, mechanism, 
  2009 							&mechanism_info);
  2010 	if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  2011 	/* if we were getting the RSA flags, save them */
  2012 	if ((crv == CKR_OK) && (mechanism == CKM_RSA_PKCS) 
  2013 						&& (!slot->hasRSAInfo)) {
  2014 	    slot->RSAInfoFlags = mechanism_info.flags;
  2015 	    slot->hasRSAInfo = PR_TRUE;
  2018     /* couldn't get the mechanism info */
  2019     if (crv != CKR_OK ) {
  2020 	return PR_TRUE;
  2022     if (keySize && ((mechanism_info.ulMinKeySize > keySize)
  2023 			|| (mechanism_info.ulMaxKeySize < keySize)) ) {
  2024 	/* Token can do mechanism, but not at the key size we
  2025 	 * want */
  2026 	return PR_TRUE;
  2028     if (mechanismInfoFlags && ((mechanism_info.flags & mechanismInfoFlags) !=
  2029 				mechanismInfoFlags) ) {
  2030 	return PR_TRUE;
  2032     return PR_FALSE;
  2036 /*
  2037  * Find the best slot which supports the given set of mechanisms and key sizes.
  2038  * In normal cases this should grab the first slot on the list with no fuss.
  2039  * The size array is presumed to match one for one with the mechanism type 
  2040  * array, which allows you to specify the required key size for each
  2041  * mechanism in the list. Whether key size is in bits or bytes is mechanism
  2042  * dependent. Typically asymetric keys are in bits and symetric keys are in 
  2043  * bytes.
  2044  */
  2045 PK11SlotInfo *
  2046 PK11_GetBestSlotMultipleWithAttributes(CK_MECHANISM_TYPE *type, 
  2047 		CK_FLAGS *mechanismInfoFlags, unsigned int *keySize, 
  2048 		unsigned int mech_count, void *wincx)
  2050     PK11SlotList *list = NULL;
  2051     PK11SlotListElement *le ;
  2052     PK11SlotInfo *slot = NULL;
  2053     PRBool freeit = PR_FALSE;
  2054     PRBool listNeedLogin = PR_FALSE;
  2055     int i;
  2056     SECStatus rv;
  2058     list = PK11_GetSlotList(type[0]);
  2060     if ((list == NULL) || (list->head == NULL)) {
  2061 	/* We need to look up all the tokens for the mechanism */
  2062 	list = PK11_GetAllTokens(type[0],PR_FALSE,PR_TRUE,wincx);
  2063 	freeit = PR_TRUE;
  2066     /* no one can do it! */
  2067     if (list == NULL) {
  2068 	PORT_SetError(SEC_ERROR_NO_TOKEN);
  2069 	return NULL;
  2072     PORT_SetError(0);
  2075     listNeedLogin = PR_FALSE;
  2076     for (i=0; i < mech_count; i++) {
  2077 	if ((type[i] != CKM_FAKE_RANDOM) && 
  2078 	    (type[i] != CKM_SHA_1) &&
  2079 	    (type[i] != CKM_SHA224) &&
  2080 	    (type[i] != CKM_SHA256) &&
  2081 	    (type[i] != CKM_SHA384) &&
  2082 	    (type[i] != CKM_SHA512) &&
  2083 	    (type[i] != CKM_MD5) && 
  2084 	    (type[i] != CKM_MD2)) {
  2085 	    listNeedLogin = PR_TRUE;
  2086 	    break;
  2090     for (le = PK11_GetFirstSafe(list); le;
  2091 			 	le = PK11_GetNextSafe(list,le,PR_TRUE)) {
  2092 	if (PK11_IsPresent(le->slot)) {
  2093 	    PRBool doExit = PR_FALSE;
  2094 	    for (i=0; i < mech_count; i++) {
  2095 	    	if (!PK11_DoesMechanism(le->slot,type[i])) {
  2096 		    doExit = PR_TRUE;
  2097 		    break;
  2099 		if ((mechanismInfoFlags && mechanismInfoFlags[i]) ||
  2100 			(keySize && keySize[i])) {
  2101 		    if (pk11_filterSlot(le->slot, type[i], 
  2102 			    mechanismInfoFlags ?  mechanismInfoFlags[i] : 0,
  2103 			    keySize ? keySize[i] : 0)) {
  2104 			doExit = PR_TRUE;
  2105 			break;
  2110 	    if (doExit) continue;
  2112 	    if (listNeedLogin && le->slot->needLogin) {
  2113 		rv = PK11_Authenticate(le->slot,PR_TRUE,wincx);
  2114 		if (rv != SECSuccess) continue;
  2116 	    slot = le->slot;
  2117 	    PK11_ReferenceSlot(slot);
  2118 	    PK11_FreeSlotListElement(list,le);
  2119 	    if (freeit) { PK11_FreeSlotList(list); }
  2120 	    return slot;
  2123     if (freeit) { PK11_FreeSlotList(list); }
  2124     if (PORT_GetError() == 0) {
  2125 	PORT_SetError(SEC_ERROR_NO_TOKEN);
  2127     return NULL;
  2130 PK11SlotInfo *
  2131 PK11_GetBestSlotMultiple(CK_MECHANISM_TYPE *type, 
  2132 			 unsigned int mech_count, void *wincx)
  2134     return PK11_GetBestSlotMultipleWithAttributes(type, NULL, NULL, 
  2135 						mech_count, wincx);
  2138 /* original get best slot now calls the multiple version with only one type */
  2139 PK11SlotInfo *
  2140 PK11_GetBestSlot(CK_MECHANISM_TYPE type, void *wincx)
  2142     return PK11_GetBestSlotMultipleWithAttributes(&type, NULL, NULL, 1, wincx);
  2145 PK11SlotInfo *
  2146 PK11_GetBestSlotWithAttributes(CK_MECHANISM_TYPE type, CK_FLAGS mechanismFlags,
  2147 		unsigned int keySize, void *wincx)
  2149     return PK11_GetBestSlotMultipleWithAttributes(&type, &mechanismFlags,
  2150 						 &keySize, 1, wincx);
  2153 int
  2154 PK11_GetBestKeyLength(PK11SlotInfo *slot,CK_MECHANISM_TYPE mechanism)
  2156     CK_MECHANISM_INFO mechanism_info;
  2157     CK_RV crv;
  2159     if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  2160     crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,
  2161                                mechanism,&mechanism_info);
  2162     if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  2163     if (crv != CKR_OK) return 0;
  2165     if (mechanism_info.ulMinKeySize == mechanism_info.ulMaxKeySize) 
  2166 		return 0;
  2167     return mechanism_info.ulMaxKeySize;
  2171 /*
  2172  * This function uses the existing PKCS #11 module to find the
  2173  * longest supported key length in the preferred token for a mechanism.
  2174  * This varies from the above function in that 1) it returns the key length
  2175  * even for fixed key algorithms, and 2) it looks through the tokens
  2176  * generally rather than for a specific token. This is used in liu of
  2177  * a PK11_GetKeyLength function in pk11mech.c since we can actually read
  2178  * supported key lengths from PKCS #11.
  2180  * For symmetric key operations the length is returned in bytes.
  2181  */
  2182 int
  2183 PK11_GetMaxKeyLength(CK_MECHANISM_TYPE mechanism)
  2185     CK_MECHANISM_INFO mechanism_info;
  2186     PK11SlotList *list = NULL;
  2187     PK11SlotListElement *le ;
  2188     PRBool freeit = PR_FALSE;
  2189     int keyLength = 0;
  2191     list = PK11_GetSlotList(mechanism);
  2193     if ((list == NULL) || (list->head == NULL)) {
  2194 	/* We need to look up all the tokens for the mechanism */
  2195 	list = PK11_GetAllTokens(mechanism,PR_FALSE,PR_FALSE,NULL);
  2196 	freeit = PR_TRUE;
  2199     /* no tokens recognize this mechanism */
  2200     if (list == NULL) {
  2201 	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
  2202 	return 0;
  2205     for (le = PK11_GetFirstSafe(list); le;
  2206 			 	le = PK11_GetNextSafe(list,le,PR_TRUE)) {
  2207 	PK11SlotInfo *slot = le->slot;
  2208 	CK_RV crv;
  2209 	if (PK11_IsPresent(slot)) {
  2210 	    if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
  2211 	    crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,
  2212                                mechanism,&mechanism_info);
  2213  	    if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
  2214 	    if ((crv == CKR_OK)  && (mechanism_info.ulMaxKeySize != 0)
  2215 		&& (mechanism_info.ulMaxKeySize != 0xffffffff)) {
  2216 		keyLength = mechanism_info.ulMaxKeySize;
  2217 		break;
  2221     if (le) 
  2222 	PK11_FreeSlotListElement(list, le);
  2223     if (freeit) 
  2224 	PK11_FreeSlotList(list);
  2225     return keyLength;
  2228 SECStatus
  2229 PK11_SeedRandom(PK11SlotInfo *slot, unsigned char *data, int len) {
  2230     CK_RV crv;
  2232     PK11_EnterSlotMonitor(slot);
  2233     crv = PK11_GETTAB(slot)->C_SeedRandom(slot->session, data, (CK_ULONG)len);
  2234     PK11_ExitSlotMonitor(slot);
  2235     if (crv != CKR_OK) {
  2236 	PORT_SetError(PK11_MapError(crv));
  2237 	return SECFailure;
  2239     return SECSuccess;
  2243 SECStatus
  2244 PK11_GenerateRandomOnSlot(PK11SlotInfo *slot, unsigned char *data, int len) {
  2245     CK_RV crv;
  2247     if (!slot->isInternal) PK11_EnterSlotMonitor(slot);
  2248     crv = PK11_GETTAB(slot)->C_GenerateRandom(slot->session,data, 
  2249 							(CK_ULONG)len);
  2250     if (!slot->isInternal) PK11_ExitSlotMonitor(slot);
  2251     if (crv != CKR_OK) {
  2252 	PORT_SetError(PK11_MapError(crv));
  2253 	return  SECFailure;
  2255     return SECSuccess;
  2258 /* Attempts to update the Best Slot for "FAKE RANDOM" generation.
  2259 ** If that's not the internal slot, then it also attempts to update the
  2260 ** internal slot.
  2261 ** The return value indicates if the INTERNAL slot was updated OK.
  2262 */
  2263 SECStatus
  2264 PK11_RandomUpdate(void *data, size_t bytes)
  2266     PK11SlotInfo *slot;
  2267     PRBool        bestIsInternal;
  2268     SECStatus     status;
  2270     slot = PK11_GetBestSlot(CKM_FAKE_RANDOM, NULL);
  2271     if (slot == NULL) {
  2272 	slot = PK11_GetInternalSlot();
  2273 	if (!slot)
  2274 	    return SECFailure;
  2277     bestIsInternal = PK11_IsInternal(slot);
  2278     status = PK11_SeedRandom(slot, data, bytes);
  2279     PK11_FreeSlot(slot);
  2281     if (!bestIsInternal) {
  2282     	/* do internal slot, too. */
  2283     	slot = PK11_GetInternalSlot();	/* can't fail */
  2284 	status = PK11_SeedRandom(slot, data, bytes);
  2285 	PK11_FreeSlot(slot);
  2287     return status;
  2291 SECStatus
  2292 PK11_GenerateRandom(unsigned char *data,int len) {
  2293     PK11SlotInfo *slot;
  2294     SECStatus rv;
  2296     slot = PK11_GetBestSlot(CKM_FAKE_RANDOM,NULL);
  2297     if (slot == NULL) return SECFailure;
  2299     rv = PK11_GenerateRandomOnSlot(slot, data, len);
  2300     PK11_FreeSlot(slot);
  2301     return rv;
  2304 /*
  2305  * Reset the token to it's initial state. For the internal module, this will
  2306  * Purge your keydb, and reset your cert db certs to USER_INIT.
  2307  */
  2308 SECStatus 
  2309 PK11_ResetToken(PK11SlotInfo *slot, char *sso_pwd)
  2311     unsigned char tokenName[32];
  2312     int tokenNameLen;
  2313     CK_RV crv;
  2315     /* reconstruct the token name */
  2316     tokenNameLen = PORT_Strlen(slot->token_name);
  2317     if (tokenNameLen > sizeof(tokenName)) {
  2318 	tokenNameLen = sizeof(tokenName);
  2321     PORT_Memcpy(tokenName,slot->token_name,tokenNameLen);
  2322     if (tokenNameLen < sizeof(tokenName)) {
  2323 	PORT_Memset(&tokenName[tokenNameLen],' ',
  2324 					 sizeof(tokenName)-tokenNameLen);
  2327     /* initialize the token */    
  2328     PK11_EnterSlotMonitor(slot);
  2330     /* first shutdown the token. Existing sessions will get closed here */
  2331     PK11_GETTAB(slot)->C_CloseAllSessions(slot->slotID);
  2332     slot->session = CK_INVALID_SESSION;
  2334     /* now re-init the token */ 
  2335     crv = PK11_GETTAB(slot)->C_InitToken(slot->slotID,
  2336 	(unsigned char *)sso_pwd, sso_pwd ? PORT_Strlen(sso_pwd): 0, tokenName);
  2338     /* finally bring the token back up */
  2339     PK11_InitToken(slot,PR_TRUE);
  2340     PK11_ExitSlotMonitor(slot);
  2341     if (crv != CKR_OK) {
  2342 	PORT_SetError(PK11_MapError(crv));
  2343 	return SECFailure;
  2345     nssTrustDomain_UpdateCachedTokenCerts(slot->nssToken->trustDomain,
  2346 	                                      slot->nssToken);
  2347     return SECSuccess;
  2349 void
  2350 PK11Slot_SetNSSToken(PK11SlotInfo *sl, NSSToken *nsst) 
  2352     sl->nssToken = nsst;
  2355 NSSToken *
  2356 PK11Slot_GetNSSToken(PK11SlotInfo *sl) 
  2358     return sl->nssToken;
  2361 /*
  2362  * wait for a token to change it's state. The application passes in the expected
  2363  * new state in event. 
  2364  */
  2365 PK11TokenStatus
  2366 PK11_WaitForTokenEvent(PK11SlotInfo *slot, PK11TokenEvent event, 
  2367 	PRIntervalTime timeout, PRIntervalTime latency, int series)
  2369    PRIntervalTime first_time = 0;
  2370    PRBool first_time_set = PR_FALSE;
  2371    PRBool waitForRemoval;
  2373    if (slot->isPerm) {
  2374 	return PK11TokenNotRemovable;
  2376    if (latency == 0) {
  2377 	latency = PR_SecondsToInterval(5);
  2379    waitForRemoval = (PRBool) (event == PK11TokenRemovedOrChangedEvent);
  2381    if (series == 0) {
  2382 	series = PK11_GetSlotSeries(slot);
  2384    while (PK11_IsPresent(slot) == waitForRemoval ) {
  2385 	PRIntervalTime interval;
  2387 	if (waitForRemoval && series != PK11_GetSlotSeries(slot)) {
  2388 	    return PK11TokenChanged;
  2390 	if (timeout == PR_INTERVAL_NO_WAIT) {
  2391 	    return waitForRemoval ? PK11TokenPresent : PK11TokenRemoved;
  2393 	if (timeout != PR_INTERVAL_NO_TIMEOUT ) {
  2394 	    interval = PR_IntervalNow();
  2395 	    if (!first_time_set) {
  2396 		first_time = interval;
  2397 		first_time_set = PR_TRUE;
  2399 	    if ((interval-first_time) > timeout) {
  2400 		return waitForRemoval ? PK11TokenPresent : PK11TokenRemoved;
  2403 	PR_Sleep(latency);
  2405    return waitForRemoval ? PK11TokenRemoved : PK11TokenPresent;

mercurial