tstellar / rpms / openldap

Forked from rpms/openldap 3 years ago
Clone
592250e
MozNSS: TLS fixes which should resolve problems with applications using multiple TLS contexts
592250e
592250e
 - context specific token description for certdb
592250e
 - store certificate object instead of nickname in in ctx
592250e
 - lock whole init and clenaup process
592250e
 - do not authenticate to a slot manually
592250e
 - do not retry when reading the pin from file
592250e
592250e
Author: Jan Vcelak <jvcelak@redhat.com>
592250e
Upstream ITS: #7312 #7313 #7314 #7315 #7316
592250e
Upstream commit: 87132b8 d07779e 3531c34 a171237 2db5195
592250e
Resolves: #795763 (and possibly other)
592250e
592250e
diff --git a/libraries/libldap/tls_m.c b/libraries/libldap/tls_m.c
592250e
index 2e755eb..4b5727b 100644
592250e
--- a/libraries/libldap/tls_m.c
592250e
+++ b/libraries/libldap/tls_m.c
592250e
@@ -81,16 +81,18 @@
592250e
 typedef struct tlsm_ctx {
592250e
 	PRFileDesc *tc_model;
592250e
 	int tc_refcnt;
592250e
+	int tc_unique; /* unique number associated with this ctx */
592250e
 	PRBool tc_verify_cert;
592250e
 	CERTCertDBHandle *tc_certdb;
592250e
-	char *tc_certname;
592250e
+	PK11SlotInfo *tc_certdb_slot;
592250e
+	CERTCertificate *tc_certificate;
592250e
+	SECKEYPrivateKey *tc_private_key;
592250e
 	char *tc_pin_file;
592250e
 	struct ldaptls *tc_config;
592250e
 	int tc_is_server;
592250e
 	int tc_require_cert;
592250e
 	PRCallOnceType tc_callonce;
592250e
 	PRBool tc_using_pem;
592250e
-	char *tc_slotname; /* if using pem */
592250e
 #ifdef HAVE_NSS_INITCONTEXT
592250e
 	NSSInitContext *tc_initctx; /* the NSS context */
592250e
 #endif
592250e
@@ -104,10 +106,16 @@ typedef struct tlsm_ctx {
592250e
 
592250e
 typedef PRFileDesc tlsm_session;
592250e
 
592250e
+static int tlsm_ctx_count;
592250e
+#define TLSM_CERTDB_DESC_FMT "ldap(%d)"
592250e
+
592250e
 static PRDescIdentity	tlsm_layer_id;
592250e
 
592250e
 static const PRIOMethods tlsm_PR_methods;
592250e
 
592250e
+#define CERTDB_NONE NULL
592250e
+#define PREFIX_NONE NULL
592250e
+
592250e
 #define PEM_LIBRARY	"nsspem"
592250e
 #define PEM_MODULE	"PEM"
592250e
 /* hash files for use with cacertdir have this file name suffix */
592250e
@@ -117,13 +125,11 @@ static const PRIOMethods tlsm_PR_methods;
592250e
 static SECMODModule *pem_module;
592250e
 
592250e
 #define DEFAULT_TOKEN_NAME "default"
592250e
-/* sprintf format used to create token name */
592250e
-#define TLSM_PEM_TOKEN_FMT "PEM Token #%ld"
592250e
+#define TLSM_PEM_SLOT_CACERTS "PEM Token #0"
592250e
+#define TLSM_PEM_SLOT_CERTS "PEM Token #1"
592250e
 
592250e
-static int tlsm_slot_count;
592250e
-
592250e
-#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
592250e
-                (x)->pValue=(v); (x)->ulValueLen = (l);
592250e
+#define PK11_SETATTRS(x,id,v,l) (x).type = (id); \
592250e
+                (x).pValue=(v); (x).ulValueLen = (l);
592250e
 
592250e
 /* forward declaration */
592250e
 static int tlsm_init( void );
592250e
@@ -134,6 +140,7 @@ static int tlsm_init( void );
592250e
    tlsm_thr_init in a non-threaded context - so we have
592250e
    to wrap the mutex creation in a prcallonce
592250e
 */
592250e
+static ldap_pvt_thread_mutex_t tlsm_ctx_count_mutex;
592250e
 static ldap_pvt_thread_mutex_t tlsm_init_mutex;
592250e
 static ldap_pvt_thread_mutex_t tlsm_pem_mutex;
592250e
 static PRCallOnceType tlsm_init_mutex_callonce = {0,0};
592250e
@@ -141,6 +148,12 @@ static PRCallOnceType tlsm_init_mutex_callonce = {0,0};
592250e
 static PRStatus PR_CALLBACK
592250e
 tlsm_thr_init_callonce( void )
592250e
 {
592250e
+	if ( ldap_pvt_thread_mutex_init( &tlsm_ctx_count_mutex ) ) {
592250e
+		Debug( LDAP_DEBUG_ANY,
592250e
+			   "TLS: could not create mutex for context counter: %d\n", errno, 0, 0 );
592250e
+		return PR_FAILURE;
592250e
+	}
592250e
+
592250e
 	if ( ldap_pvt_thread_mutex_init( &tlsm_init_mutex ) ) {
592250e
 		Debug( LDAP_DEBUG_ANY,
592250e
 			   "TLS: could not create mutex for moznss initialization: %d\n", errno, 0, 0 );
592250e
@@ -890,6 +903,8 @@ tlsm_get_pin(PK11SlotInfo *slot, PRBool retry, tlsm_ctx *ctx)
592250e
 	 */
592250e
 	if ( ctx->tc_pin_file ) {
592250e
 		pwdstr = tlsm_get_pin_from_file( token_name, ctx );
592250e
+		if (retry && pwdstr != NULL)
592250e
+			return NULL;
592250e
 	}
592250e
 #endif /* RETRIEVE_PASSWORD_FROM_FILE */
592250e
 #ifdef READ_PASSWORD_FROM_STDIN
592250e
@@ -932,6 +947,15 @@ tlsm_pin_prompt(PK11SlotInfo *slot, PRBool retry, void *arg)
592250e
 	return tlsm_get_pin( slot, retry, ctx );
592250e
 }
592250e
 
592250e
+static char *
592250e
+tlsm_ctx_subject_name(tlsm_ctx *ctx)
592250e
+{
592250e
+	if (!ctx || !ctx->tc_certificate)
592250e
+		return "(unknown)";
592250e
+
592250e
+	return ctx->tc_certificate->subjectName;
592250e
+}
592250e
+
592250e
 static SECStatus
592250e
 tlsm_get_basic_constraint_extension( CERTCertificate *cert,
592250e
 									 CERTBasicConstraints *cbcval )
592250e
@@ -1088,25 +1112,6 @@ tlsm_auth_cert_handler(void *arg, PRFileDesc *fd,
592250e
 	return ret;
592250e
 }
592250e
 
592250e
-static int
592250e
-tlsm_authenticate_to_slot( tlsm_ctx *ctx, PK11SlotInfo *slot )
592250e
-{
592250e
-	int rc = -1;
592250e
-
592250e
-	if ( SECSuccess != PK11_Authenticate( slot, PR_FALSE, ctx ) ) {
592250e
-		char *token_name = PK11_GetTokenName( slot );
592250e
-		PRErrorCode errcode = PR_GetError();
592250e
-		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: could not authenticate to the security token %s - error %d:%s.\n",
592250e
-			   token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
592250e
-			   PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
-	} else {
592250e
-		rc = 0; /* success */
592250e
-	}
592250e
-
592250e
-	return rc;
592250e
-}
592250e
-
592250e
 static SECStatus
592250e
 tlsm_nss_shutdown_cb( void *appData, void *nssData )
592250e
 {
592250e
@@ -1196,22 +1201,18 @@ tlsm_free_pem_objs( tlsm_ctx *ctx )
592250e
 }
592250e
 
592250e
 static int
592250e
-tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca, PRBool istrusted )
592250e
+tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca )
592250e
 {
592250e
-	CK_SLOT_ID slotID;
592250e
-	PK11SlotInfo *slot = NULL;
592250e
-	PK11GenericObject *rv;
592250e
-	CK_ATTRIBUTE *attrs;
592250e
-	CK_ATTRIBUTE theTemplate[20];
592250e
+	PK11SlotInfo *slot;
592250e
+	PK11GenericObject *cert;
592250e
+	CK_ATTRIBUTE attrs[4];
592250e
 	CK_BBOOL cktrue = CK_TRUE;
592250e
 	CK_BBOOL ckfalse = CK_FALSE;
592250e
 	CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
592250e
-	char tmpslotname[64];
592250e
-	char *slotname = NULL;
592250e
-	const char *ptr = NULL;
592250e
-	char sep = PR_GetDirectorySeparator();
592250e
+	char *slotname;
592250e
 	PRFileInfo fi;
592250e
 	PRStatus status;
592250e
+	SECItem certDER = { 0, NULL, 0 };
592250e
 
592250e
 	memset( &fi, 0, sizeof(fi) );
592250e
 	status = PR_GetFileInfo( filename, &fi );
592250e
@@ -1232,87 +1233,96 @@ tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca, PRBoo
592250e
 		return -1;
592250e
 	}
592250e
 
592250e
-	attrs = theTemplate;
592250e
+	slotname = isca ? TLSM_PEM_SLOT_CACERTS : TLSM_PEM_SLOT_CERTS;
592250e
+	slot = PK11_FindSlotByName( slotname );
592250e
 
592250e
-	if ( isca ) {
592250e
-		slotID = 0; /* CA and trust objects use slot 0 */
592250e
-		PR_snprintf( tmpslotname, sizeof(tmpslotname), TLSM_PEM_TOKEN_FMT, slotID );
592250e
-		slotname = tmpslotname;
592250e
-		istrusted = PR_TRUE;
592250e
-	} else {
592250e
-		if ( ctx->tc_slotname == NULL ) { /* need new slot */
592250e
-			if ( istrusted ) {
592250e
-				slotID = 0;
592250e
-			} else {
592250e
-				slotID = ++tlsm_slot_count;
592250e
-			}
592250e
-			ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
592250e
-		}
592250e
-		slotname = ctx->tc_slotname;
592250e
-
592250e
-		if ( ( ptr = PL_strrchr( filename, sep ) ) ) {
592250e
-			PL_strfree( ctx->tc_certname );
592250e
-			++ptr;
592250e
-			if ( istrusted ) {
592250e
-				/* pemnss conflates trusted certs with CA certs - since there can
592250e
-				   be more than one CA cert in a file (e.g. ca-bundle.crt) pemnss
592250e
-				   numbers each trusted cert - in the case of a server cert, there will be
592250e
-				   only one, so it will be number 0 */
592250e
-				ctx->tc_certname = PR_smprintf( "%s:%s - 0", slotname, ptr );
592250e
-			} else {
592250e
-				ctx->tc_certname = PR_smprintf( "%s:%s", slotname, ptr );
592250e
-			}
592250e
-		}
592250e
+	if ( !slot ) {
592250e
+		PRErrorCode errcode = PR_GetError();
592250e
+		Debug( LDAP_DEBUG_ANY,
592250e
+			   "TLS: could not find the slot for the certificate '%s' - error %d:%s.\n",
592250e
+			   filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+		return -1;
592250e
 	}
592250e
 
592250e
-	slot = PK11_FindSlotByName( slotname );
592250e
+	PK11_SETATTRS( attrs[0], CKA_CLASS, &objClass, sizeof(objClass) );
592250e
+	PK11_SETATTRS( attrs[1], CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) );
592250e
+	PK11_SETATTRS( attrs[2], CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 );
592250e
+	PK11_SETATTRS( attrs[3], CKA_TRUST, isca ? &cktrue : &ckfalse, sizeof(CK_BBOOL) );
592250e
 
592250e
-	if ( !slot ) {
592250e
+	cert = PK11_CreateGenericObject( slot, attrs, 4, PR_FALSE /* isPerm */ );
592250e
+
592250e
+	if ( !cert ) {
592250e
 		PRErrorCode errcode = PR_GetError();
592250e
 		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: could not find the slot for certificate %s - error %d:%s.\n",
592250e
-			   ctx->tc_certname, errcode,
592250e
-			   PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+			   "TLS: could not add the certificate '%s' - error %d:%s.\n",
592250e
+			   filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+		PK11_FreeSlot( slot );
592250e
 		return -1;
592250e
 	}
592250e
 
592250e
-	PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
592250e
-	PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
592250e
-	PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
592250e
-	if ( istrusted ) {
592250e
-		PK11_SETATTRS( attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) ); attrs++;
592250e
-	} else {
592250e
-		PK11_SETATTRS( attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) ); attrs++;
592250e
+	/* if not CA, we store the certificate in ctx->tc_certificate */
592250e
+	if ( !isca ) {
592250e
+		if ( PK11_ReadRawAttribute( PK11_TypeGeneric, cert, CKA_VALUE, &certDER ) != SECSuccess ) {
592250e
+			PRErrorCode errcode = PR_GetError();
592250e
+			Debug( LDAP_DEBUG_ANY,
592250e
+					"TLS: could not get DER of the '%s' certificate - error %d:%s.\n",
592250e
+					filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+			PK11_DestroyGenericObject( cert );
592250e
+			PK11_FreeSlot( slot );
592250e
+			return -1;
592250e
+		}
592250e
+
592250e
+		ctx->tc_certificate = PK11_FindCertFromDERCertItem( slot, &certDER, NULL );
592250e
+		SECITEM_FreeItem( &certDER, PR_FALSE );
592250e
+
592250e
+		if ( !ctx->tc_certificate ) {
592250e
+			PRErrorCode errcode = PR_GetError();
592250e
+			Debug( LDAP_DEBUG_ANY,
592250e
+					"TLS: could not get certificate '%s' using DER - error %d:%s.\n",
592250e
+					filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+			PK11_DestroyGenericObject( cert );
592250e
+			PK11_FreeSlot( slot );
592250e
+			return -1;
592250e
+		}
592250e
 	}
592250e
-	/* This loads the certificate in our PEM module into the appropriate
592250e
-	 * slot.
592250e
-	 */
592250e
-	rv = PK11_CreateGenericObject( slot, theTemplate, 4, PR_FALSE /* isPerm */ );
592250e
+
592250e
+	tlsm_add_pem_obj( ctx, cert );
592250e
 
592250e
 	PK11_FreeSlot( slot );
592250e
 
592250e
-	if ( !rv ) {
592250e
+	return 0;
592250e
+}
592250e
+
592250e
+static int
592250e
+tlsm_ctx_load_private_key(tlsm_ctx *ctx)
592250e
+{
592250e
+	if (!ctx->tc_certificate)
592250e
+		return -1;
592250e
+
592250e
+	if (ctx->tc_private_key)
592250e
+		return 0;
592250e
+
592250e
+	void *pin_arg = SSL_RevealPinArg(ctx->tc_model);
592250e
+
592250e
+	ctx->tc_private_key = PK11_FindKeyByAnyCert(ctx->tc_certificate, pin_arg);
592250e
+	if (!ctx->tc_private_key) {
592250e
 		PRErrorCode errcode = PR_GetError();
592250e
-		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: could not add the certificate %s - error %d:%s.\n",
592250e
-			   ctx->tc_certname, errcode,
592250e
-			   PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+		Debug(LDAP_DEBUG_ANY,
592250e
+				"TLS: cannot find private key for certificate '%s' (error %d: %s)",
592250e
+				tlsm_ctx_subject_name(ctx), errcode,
592250e
+				PR_ErrorToString(errcode, PR_LANGUAGE_I_DEFAULT));
592250e
 		return -1;
592250e
 	}
592250e
 
592250e
-	tlsm_add_pem_obj( ctx, rv );
592250e
-
592250e
 	return 0;
592250e
 }
592250e
 
592250e
 static int
592250e
 tlsm_add_key_from_file( tlsm_ctx *ctx, const char *filename )
592250e
 {
592250e
-	CK_SLOT_ID slotID;
592250e
 	PK11SlotInfo * slot = NULL;
592250e
-	PK11GenericObject *rv;
592250e
-	CK_ATTRIBUTE *attrs;
592250e
-	CK_ATTRIBUTE theTemplate[20];
592250e
+	PK11GenericObject *key;
592250e
+	CK_ATTRIBUTE attrs[3];
592250e
 	CK_BBOOL cktrue = CK_TRUE;
592250e
 	CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
592250e
 	int retcode = 0;
592250e
@@ -1338,48 +1348,40 @@ tlsm_add_key_from_file( tlsm_ctx *ctx, const char *filename )
592250e
 		return -1;
592250e
 	}
592250e
 
592250e
-	attrs = theTemplate;
592250e
-
592250e
-	if ( ctx->tc_slotname == NULL ) { /* need new slot */
592250e
-		slotID = ++tlsm_slot_count;
592250e
-		ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
592250e
-	}
592250e
-	slot = PK11_FindSlotByName( ctx->tc_slotname );
592250e
+	slot = PK11_FindSlotByName( TLSM_PEM_SLOT_CERTS );
592250e
 
592250e
 	if ( !slot ) {
592250e
 		PRErrorCode errcode = PR_GetError();
592250e
 		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: could not find the slot %s for the private key - error %d:%s.\n",
592250e
-			   ctx->tc_slotname, errcode,
592250e
-			   PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+			   "TLS: could not find the slot for the private key '%s' - error %d:%s.\n",
592250e
+			   filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
 		return -1;
592250e
 	}
592250e
 
592250e
-	PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
592250e
-	PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
592250e
-	PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
592250e
-	rv = PK11_CreateGenericObject( slot, theTemplate, 3, PR_FALSE /* isPerm */ );
592250e
+	PK11_SETATTRS( attrs[0], CKA_CLASS, &objClass, sizeof(objClass) );
592250e
+	PK11_SETATTRS( attrs[1], CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) );
592250e
+	PK11_SETATTRS( attrs[2], CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 );
592250e
+
592250e
+	key = PK11_CreateGenericObject( slot, attrs, 3, PR_FALSE /* isPerm */ );
592250e
 
592250e
-	if ( !rv ) {
592250e
+	if ( !key ) {
592250e
 		PRErrorCode errcode = PR_GetError();
592250e
 		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: could not add the certificate %s - error %d:%s.\n",
592250e
-			   ctx->tc_certname, errcode,
592250e
-			   PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+			   "TLS: could not add the private key '%s' - error %d:%s.\n",
592250e
+			   filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
 		retcode = -1;
592250e
 	} else {
592250e
+		tlsm_add_pem_obj( ctx, key );
592250e
+		retcode = 0;
592250e
+
592250e
 		/* When adding an encrypted key the PKCS#11 will be set as removed */
592250e
 		/* This will force the token to be seen as re-inserted */
592250e
 		SECMOD_WaitForAnyTokenEvent( pem_module, 0, 0 );
592250e
 		PK11_IsPresent( slot );
592250e
-		retcode = 0;
592250e
 	}
592250e
 
592250e
 	PK11_FreeSlot( slot );
592250e
 
592250e
-	if ( !retcode ) {
592250e
-		tlsm_add_pem_obj( ctx, rv );
592250e
-	}
592250e
 	return retcode;
592250e
 }
592250e
 
592250e
@@ -1396,7 +1398,7 @@ tlsm_init_ca_certs( tlsm_ctx *ctx, const char *cacertfile, const char *cacertdir
592250e
 	}
592250e
 
592250e
 	if ( cacertfile ) {
592250e
-		int rc = tlsm_add_cert_from_file( ctx, cacertfile, isca, PR_TRUE );
592250e
+		int rc = tlsm_add_cert_from_file( ctx, cacertfile, isca );
592250e
 		if ( rc ) {
592250e
 			errcode = PR_GetError();
592250e
 			Debug( LDAP_DEBUG_ANY,
592250e
@@ -1470,7 +1472,7 @@ tlsm_init_ca_certs( tlsm_ctx *ctx, const char *cacertfile, const char *cacertdir
592250e
 					continue;
592250e
 				}
592250e
 				fullpath = PR_smprintf( "%s/%s", cacertdir, entry->name );
592250e
-				if ( !tlsm_add_cert_from_file( ctx, fullpath, isca, PR_TRUE ) ) {
592250e
+				if ( !tlsm_add_cert_from_file( ctx, fullpath, isca ) ) {
592250e
 					Debug( LDAP_DEBUG_TRACE,
592250e
 						   "TLS: loaded CA certificate file %s from CA certificate directory %s.\n",
592250e
 						   fullpath, cacertdir, 0 );
592250e
@@ -1534,6 +1536,45 @@ tlsm_get_certdb_prefix( const char *certdir, char **realcertdir, char **prefix )
592250e
 }
592250e
 
592250e
 /*
592250e
+ * Currently mutiple MozNSS contexts share one certificate storage. When the
592250e
+ * certdb is being opened, only new certificates are added to the storage.
592250e
+ * When different databases are used, conflicting nicknames make the
592250e
+ * certificate lookup by the nickname impossible. In addition a token
592250e
+ * description might be prepended in certain conditions.
592250e
+ *
592250e
+ * In order to make the certificate lookup by nickname possible, we explicitly
592250e
+ * open each database using SECMOD_OpenUserDB and assign it the token
592250e
+ * description. The token description is generated using ctx->tc_unique value,
592250e
+ * which is unique for each context.
592250e
+ */
592250e
+static PK11SlotInfo *
592250e
+tlsm_init_open_certdb(tlsm_ctx *ctx, const char *dbdir, const char *prefix)
592250e
+{
592250e
+	PK11SlotInfo *slot = NULL;
592250e
+	char *token_desc = NULL;
592250e
+	char *config = NULL;
592250e
+
592250e
+	token_desc = PR_smprintf(TLSM_CERTDB_DESC_FMT, ctx->tc_unique);
592250e
+	config = PR_smprintf("configDir='%s' tokenDescription='%s' certPrefix='%s' keyPrefix='%s' flags=readOnly",
592250e
+										dbdir, token_desc, prefix, prefix);
592250e
+	Debug(LDAP_DEBUG_TRACE, "TLS: certdb config: %s\n", config, 0, 0);
592250e
+
592250e
+	slot = SECMOD_OpenUserDB(config);
592250e
+	if (!slot) {
592250e
+		PRErrorCode errcode = PR_GetError();
592250e
+		Debug(LDAP_DEBUG_TRACE, "TLS: cannot open certdb '%s', error %d:%s\n", dbdir, errcode,
592250e
+							PR_ErrorToString(errcode, PR_LANGUAGE_I_DEFAULT));
592250e
+	}
592250e
+
592250e
+	if (token_desc)
592250e
+		PR_smprintf_free(token_desc);
592250e
+	if (config)
592250e
+		PR_smprintf_free(config);
592250e
+
592250e
+	return slot;
592250e
+}
592250e
+
592250e
+/*
592250e
  * This is the part of the init we defer until we get the
592250e
  * actual security configuration information.  This is
592250e
  * only called once, protected by a PRCallOnce
592250e
@@ -1553,6 +1594,7 @@ tlsm_deferred_init( void *arg )
592250e
 #ifdef HAVE_NSS_INITCONTEXT
592250e
 	NSSInitParameters initParams;
592250e
 	NSSInitContext *initctx = NULL;
592250e
+	PK11SlotInfo *certdb_slot = NULL;
592250e
 #endif
592250e
 	SECStatus rc;
592250e
 	int done = 0;
592250e
@@ -1613,28 +1655,37 @@ tlsm_deferred_init( void *arg )
592250e
 			}
592250e
 
592250e
 			tlsm_get_certdb_prefix( securitydir, &realcertdir, &prefix );
592250e
-			LDAP_MUTEX_LOCK( &tlsm_init_mutex );
592250e
 
592250e
+			/* initialize only moddb; certdb will be initialized explicitly */
592250e
 #ifdef HAVE_NSS_INITCONTEXT
592250e
 #ifdef INITCONTEXT_HACK
592250e
 			if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
592250e
 				rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
592250e
 			} else {
592250e
 				initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
592250e
-										   &initParams, NSS_INIT_READONLY );
592250e
-				rc = (initctx == NULL) ? SECFailure : SECSuccess;
592250e
+								   &initParams, NSS_INIT_READONLY|NSS_INIT_NOCERTDB );
592250e
 			}
592250e
 #else
592250e
 			initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
592250e
-									   &initParams, NSS_INIT_READONLY );
592250e
-			rc = (initctx == NULL) ? SECFailure : SECSuccess;
592250e
+								   &initParams, NSS_INIT_READONLY|NSS_INIT_NOCERTDB );
592250e
 #endif
592250e
+			rc = SECFailure;
592250e
+
592250e
+			if (initctx != NULL) {
592250e
+				certdb_slot = tlsm_init_open_certdb(ctx, realcertdir, prefix);
592250e
+				if (certdb_slot) {
592250e
+					rc = SECSuccess;
592250e
+					ctx->tc_initctx = initctx;
592250e
+					ctx->tc_certdb_slot = certdb_slot;
592250e
+				} else {
592250e
+					NSS_ShutdownContext(initctx);
592250e
+					initctx = NULL;
592250e
+				}
592250e
+			}
592250e
 #else
592250e
 			rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
592250e
 #endif
592250e
 
592250e
-			LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
-
592250e
 			if ( rc != SECSuccess ) {
592250e
 				errcode = PORT_GetError();
592250e
 				if ( securitydirs[ii] != lt->lt_cacertdir) {
592250e
@@ -1658,26 +1709,29 @@ tlsm_deferred_init( void *arg )
592250e
 		}
592250e
 
592250e
 		if ( errcode ) { /* no moznss db found, or not using moznss db */
592250e
-			LDAP_MUTEX_LOCK( &tlsm_init_mutex );
592250e
 #ifdef HAVE_NSS_INITCONTEXT
592250e
 			int flags = NSS_INIT_READONLY|NSS_INIT_NOCERTDB|NSS_INIT_NOMODDB;
592250e
 #ifdef INITCONTEXT_HACK
592250e
 			if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
592250e
 				rc = NSS_NoDB_Init( NULL );
592250e
 			} else {
592250e
-				initctx = NSS_InitContext( "", "", "", SECMOD_DB,
592250e
+				initctx = NSS_InitContext( CERTDB_NONE, PREFIX_NONE, PREFIX_NONE, SECMOD_DB,
592250e
 										   &initParams, flags );
592250e
 				rc = (initctx == NULL) ? SECFailure : SECSuccess;
592250e
 			}
592250e
 #else
592250e
-			initctx = NSS_InitContext( "", "", "", SECMOD_DB,
592250e
+			initctx = NSS_InitContext( CERTDB_NONE, PREFIX_NONE, PREFIX_NONE, SECMOD_DB,
592250e
 									   &initParams, flags );
592250e
-			rc = (initctx == NULL) ? SECFailure : SECSuccess;
592250e
+			if (initctx) {
592250e
+				ctx->tc_initctx = initctx;
592250e
+				rc = SECSuccess;
592250e
+			} else {
592250e
+				rc = SECFailure;
592250e
+			}
592250e
 #endif
592250e
 #else
592250e
 			rc = NSS_NoDB_Init( NULL );
592250e
 #endif
592250e
-			LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
 			if ( rc != SECSuccess ) {
592250e
 				errcode = PORT_GetError();
592250e
 				Debug( LDAP_DEBUG_ANY,
592250e
@@ -1685,18 +1739,11 @@ tlsm_deferred_init( void *arg )
592250e
 					   errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
592250e
 				return -1;
592250e
 			}
592250e
-
592250e
-#ifdef HAVE_NSS_INITCONTEXT
592250e
-			ctx->tc_initctx = initctx;
592250e
-#endif
592250e
-
592250e
 		}
592250e
 
592250e
 		if ( errcode || lt->lt_cacertfile ) {
592250e
 			/* initialize the PEM module */
592250e
-			LDAP_MUTEX_LOCK( &tlsm_init_mutex );
592250e
 			if ( tlsm_init_pem_module() ) {
592250e
-				LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
 				int pem_errcode = PORT_GetError();
592250e
 				Debug( LDAP_DEBUG_ANY,
592250e
 					   "TLS: could not initialize moznss PEM module - error %d:%s.\n",
592250e
@@ -1708,7 +1755,6 @@ tlsm_deferred_init( void *arg )
592250e
 			} else if ( !errcode ) {
592250e
 				tlsm_init_ca_certs( ctx, lt->lt_cacertfile, NULL );
592250e
 			}
592250e
-			LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
 		}
592250e
 
592250e
 		if ( errcode ) {
592250e
@@ -1734,12 +1780,6 @@ tlsm_deferred_init( void *arg )
592250e
 			ctx->tc_using_pem = PR_TRUE;
592250e
 		}
592250e
 
592250e
-#ifdef HAVE_NSS_INITCONTEXT
592250e
-		if ( !ctx->tc_initctx ) {
592250e
-			ctx->tc_initctx = initctx;
592250e
-		}
592250e
-#endif
592250e
-
592250e
 		NSS_SetDomesticPolicy();
592250e
 
592250e
 		PK11_SetPasswordFunc( tlsm_pin_prompt );
592250e
@@ -1754,10 +1794,8 @@ tlsm_deferred_init( void *arg )
592250e
 		}
592250e
 
592250e
 		if  ( ctx->tc_is_server ) {
592250e
-			LDAP_MUTEX_LOCK( &tlsm_init_mutex );
592250e
 			/* 0 means use the defaults here */
592250e
 			SSL_ConfigServerSessionIDCache( 0, 0, 0, NULL );
592250e
-			LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
 		}
592250e
 
592250e
 #ifndef HAVE_NSS_INITCONTEXT
592250e
@@ -1767,137 +1805,34 @@ tlsm_deferred_init( void *arg )
592250e
 	return 0;
592250e
 }
592250e
 
592250e
-static int
592250e
-tlsm_authenticate( tlsm_ctx *ctx, const char *certname, const char *pininfo )
592250e
-{
592250e
-	const char *colon = NULL;
592250e
-	char *token_name = NULL;
592250e
-	PK11SlotInfo *slot = NULL;
592250e
-	int rc = -1;
592250e
-
592250e
-	if ( !certname || !*certname ) {
592250e
-		return 0;
592250e
-	}
592250e
-
592250e
-	if ( ( colon = PL_strchr( certname, ':' ) ) ) {
592250e
-		token_name = PL_strndup( certname, colon-certname );
592250e
-	}
592250e
-
592250e
-	if ( token_name ) {
592250e
-		slot = PK11_FindSlotByName( token_name );
592250e
-	} else {
592250e
-		slot = PK11_GetInternalKeySlot();
592250e
-	}
592250e
-
592250e
-	if ( !slot ) {
592250e
-		PRErrorCode errcode = PR_GetError();
592250e
-		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: could not find the slot for security token %s - error %d:%s.\n",
592250e
-			   token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
592250e
-			   PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
-		goto done;
592250e
-	}
592250e
-
592250e
-	rc = tlsm_authenticate_to_slot( ctx, slot );
592250e
-
592250e
-done:
592250e
-	PL_strfree( token_name );
592250e
-	if ( slot ) {
592250e
-		PK11_FreeSlot( slot );
592250e
-	}
592250e
-
592250e
-	return rc;
592250e
-}
592250e
-
592250e
 /*
592250e
  * Find and verify the certificate.
592250e
- * Either fd is given, in which case the cert will be taken from it via SSL_PeerCertificate
592250e
- * or certname is given, and it will be searched for by name
592250e
+ * The key is loaded and stored in ctx->tc_private_key
592250e
  */
592250e
 static int
592250e
-tlsm_find_and_verify_cert_key(tlsm_ctx *ctx, PRFileDesc *fd, const char *certname, int isServer, CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey)
592250e
+tlsm_find_and_verify_cert_key(tlsm_ctx *ctx)
592250e
 {
592250e
-	CERTCertificate *cert = NULL;
592250e
-	int rc = -1;
592250e
-	void *pin_arg = NULL;
592250e
-	SECKEYPrivateKey *key = NULL;
592250e
+	SECCertificateUsage certUsage;
592250e
+	PRBool checkSig;
592250e
+	SECStatus status;
592250e
+	int errorToIgnore;
592250e
+	void *pin_arg;
592250e
 
592250e
-	pin_arg = SSL_RevealPinArg( fd );
592250e
-	if ( certname ) {
592250e
-		cert = PK11_FindCertFromNickname( certname, pin_arg );
592250e
-		if ( !cert ) {
592250e
-			PRErrorCode errcode = PR_GetError();
592250e
-			Debug( LDAP_DEBUG_ANY,
592250e
-				   "TLS: error: the certificate %s could not be found in the database - error %d:%s\n",
592250e
-				   certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
-			return -1;
592250e
-		}
592250e
-	} else {
592250e
-		/* we are verifying the peer cert
592250e
-		   we also need to swap the isServer meaning */
592250e
-		cert = SSL_PeerCertificate( fd );
592250e
-		if ( !cert ) {
592250e
-			PRErrorCode errcode = PR_GetError();
592250e
-			Debug( LDAP_DEBUG_ANY,
592250e
-				   "TLS: error: could not get the certificate from the peer connection - error %d:%s\n",
592250e
-				   errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), NULL );
592250e
-			return -1;
592250e
-		}
592250e
-		isServer = !isServer; /* verify the peer's cert instead */
592250e
-	}
592250e
-
592250e
-	if ( ctx->tc_slotname ) {
592250e
-		PK11SlotInfo *slot = PK11_FindSlotByName( ctx->tc_slotname );
592250e
-		key = PK11_FindPrivateKeyFromCert( slot, cert, NULL );
592250e
-		PK11_FreeSlot( slot );
592250e
-	} else {
592250e
-		key = PK11_FindKeyByAnyCert( cert, pin_arg );
592250e
-	}
592250e
-
592250e
-	if (key) {
592250e
-		SECCertificateUsage certUsage;
592250e
-		PRBool checkSig = PR_TRUE;
592250e
-		SECStatus status;
592250e
-		/* may not have a CA cert - ok - ignore SEC_ERROR_UNKNOWN_ISSUER */
592250e
-		int errorToIgnore = SEC_ERROR_UNKNOWN_ISSUER;
592250e
+	if (tlsm_ctx_load_private_key(ctx))
592250e
+		return -1;
592250e
 
592250e
-		if ( pRetKey ) {
592250e
-			*pRetKey = key; /* caller will deal with this */
592250e
-		} else {
592250e
-			SECKEY_DestroyPrivateKey( key );
592250e
-		}
592250e
-		if ( isServer ) {
592250e
-			certUsage = certificateUsageSSLServer;
592250e
-		} else {
592250e
-			certUsage = certificateUsageSSLClient;
592250e
-		}
592250e
-		if ( ctx->tc_verify_cert ) {
592250e
-			checkSig = PR_TRUE;
592250e
-		} else {
592250e
-			checkSig = PR_FALSE;
592250e
-		}
592250e
-		if ( ctx->tc_warn_only ) {
592250e
-			errorToIgnore = -1;
592250e
-		}
592250e
-		status = tlsm_verify_cert( ctx->tc_certdb, cert, pin_arg,
592250e
-								   checkSig, certUsage, errorToIgnore );
592250e
-		if ( status == SECSuccess ) {
592250e
-			rc = 0;
592250e
-		}
592250e
-	} else {
592250e
-		PRErrorCode errcode = PR_GetError();
592250e
-		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: error: could not find the private key for certificate %s - error %d:%s\n",
592250e
-			   certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
-	}
592250e
+	pin_arg = SSL_RevealPinArg(ctx->tc_model);
592250e
+	certUsage = ctx->tc_is_server ? certificateUsageSSLServer : certificateUsageSSLClient;
592250e
+	checkSig = ctx->tc_verify_cert ? PR_TRUE : PR_FALSE;
592250e
+	if ( ctx->tc_warn_only )
592250e
+		errorToIgnore = -1;
592250e
+	else
592250e
+		errorToIgnore = SEC_ERROR_UNKNOWN_ISSUER; /* may not have a CA cert */
592250e
 
592250e
-	if ( pRetCert ) {
592250e
-		*pRetCert = cert; /* caller will deal with this */
592250e
-	} else {
592250e
-		CERT_DestroyCertificate( cert );
592250e
-	}
592250e
+	status = tlsm_verify_cert( ctx->tc_certdb, ctx->tc_certificate, pin_arg,
592250e
+							   checkSig, certUsage, errorToIgnore );
592250e
 
592250e
-    return rc;
592250e
+	return status == SECSuccess ? 0 : -1;
592250e
 }
592250e
 
592250e
 static int
592250e
@@ -1906,39 +1841,18 @@ tlsm_get_client_auth_data( void *arg, PRFileDesc *fd,
592250e
 						   SECKEYPrivateKey **pRetKey )
592250e
 {
592250e
 	tlsm_ctx *ctx = (tlsm_ctx *)arg;
592250e
-	int rc;
592250e
-	PRBool saveval;
592250e
 
592250e
-	/* don't need caNames - this function will call CERT_VerifyCertificateNow
592250e
-	   which will verify the cert against the known CAs */
592250e
-	saveval = ctx->tc_warn_only;
592250e
-	ctx->tc_warn_only = PR_TRUE;
592250e
-	rc = tlsm_find_and_verify_cert_key( ctx, fd, ctx->tc_certname, 0, pRetCert, pRetKey );
592250e
-	ctx->tc_warn_only = saveval;
592250e
-	if ( rc ) {
592250e
-		Debug( LDAP_DEBUG_ANY,
592250e
-			   "TLS: error: unable to perform client certificate authentication for "
592250e
-			   "certificate named %s\n", ctx->tc_certname, 0, 0 );
592250e
-		if ( pRetKey && *pRetKey ) {
592250e
-			SECKEY_DestroyPrivateKey( *pRetKey );
592250e
-			*pRetKey = NULL;
592250e
-		}
592250e
-		if ( pRetCert && *pRetCert ) {
592250e
-			CERT_DestroyCertificate( *pRetCert );
592250e
-			*pRetCert = NULL;
592250e
-		}
592250e
-		return SECFailure;
592250e
-	}
592250e
+	if (pRetCert)
592250e
+		*pRetCert = CERT_DupCertificate(ctx->tc_certificate);
592250e
+
592250e
+	if (pRetKey)
592250e
+		*pRetKey = SECKEY_CopyPrivateKey(ctx->tc_private_key);
592250e
 
592250e
 	return SECSuccess;
592250e
 }
592250e
 
592250e
 /*
592250e
  * ctx must have a tc_model that is valid
592250e
- * certname is in the form [<tokenname>:]<certnickname>
592250e
- * where <tokenname> is the name of the PKCS11 token
592250e
- * and <certnickname> is the nickname of the cert/key in
592250e
- * the database
592250e
 */
592250e
 static int
592250e
 tlsm_clientauth_init( tlsm_ctx *ctx )
592250e
@@ -1949,12 +1863,12 @@ tlsm_clientauth_init( tlsm_ctx *ctx )
592250e
 
592250e
 	saveval = ctx->tc_warn_only;
592250e
 	ctx->tc_warn_only = PR_TRUE;
592250e
-	rc = tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, 0, NULL, NULL );
592250e
+	rc = tlsm_find_and_verify_cert_key(ctx);
592250e
 	ctx->tc_warn_only = saveval;
592250e
 	if ( rc ) {
592250e
 		Debug( LDAP_DEBUG_ANY,
592250e
 			   "TLS: error: unable to set up client certificate authentication for "
592250e
-			   "certificate named %s\n", ctx->tc_certname, 0, 0 );
592250e
+			   "certificate named %s\n", tlsm_ctx_subject_name(ctx), 0, 0 );
592250e
 		return -1;
592250e
 	}
592250e
 
592250e
@@ -1972,6 +1886,7 @@ static void
592250e
 tlsm_destroy( void )
592250e
 {
592250e
 #ifdef LDAP_R_COMPILE
592250e
+	ldap_pvt_thread_mutex_destroy( &tlsm_ctx_count_mutex );
592250e
 	ldap_pvt_thread_mutex_destroy( &tlsm_init_mutex );
592250e
 	ldap_pvt_thread_mutex_destroy( &tlsm_pem_mutex );
592250e
 #endif
592250e
@@ -2048,16 +1963,20 @@ tlsm_ctx_new ( struct ldapoptions *lo )
592250e
 #ifdef LDAP_R_COMPILE
592250e
 		ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
592250e
 #endif
592250e
+		LDAP_MUTEX_LOCK( &tlsm_ctx_count_mutex );
592250e
+		ctx->tc_unique = tlsm_ctx_count++;
592250e
+		LDAP_MUTEX_UNLOCK( &tlsm_ctx_count_mutex );
592250e
 		ctx->tc_config = NULL; /* populated later by tlsm_ctx_init */
592250e
 		ctx->tc_certdb = NULL;
592250e
-		ctx->tc_certname = NULL;
592250e
+		ctx->tc_certdb_slot = NULL;
592250e
+		ctx->tc_certificate = NULL;
592250e
+		ctx->tc_private_key = NULL;
592250e
 		ctx->tc_pin_file = NULL;
592250e
 		ctx->tc_model = NULL;
592250e
 		memset(&ctx->tc_callonce, 0, sizeof(ctx->tc_callonce));
592250e
 		ctx->tc_require_cert = lo->ldo_tls_require_cert;
592250e
 		ctx->tc_verify_cert = PR_FALSE;
592250e
 		ctx->tc_using_pem = PR_FALSE;
592250e
-		ctx->tc_slotname = NULL;
592250e
 #ifdef HAVE_NSS_INITCONTEXT
592250e
 		ctx->tc_initctx = NULL;
592250e
 #endif /* HAVE_NSS_INITCONTEXT */
592250e
@@ -2090,28 +2009,38 @@ tlsm_ctx_free ( tls_ctx *ctx )
592250e
 	LDAP_MUTEX_UNLOCK( &c->tc_refmutex );
592250e
 	if ( refcount )
592250e
 		return;
592250e
+
592250e
+	LDAP_MUTEX_LOCK( &tlsm_init_mutex );
592250e
 	if ( c->tc_model )
592250e
 		PR_Close( c->tc_model );
592250e
+	if (c->tc_certificate)
592250e
+		CERT_DestroyCertificate(c->tc_certificate);
592250e
+	if (c->tc_private_key)
592250e
+		SECKEY_DestroyPrivateKey(c->tc_private_key);
592250e
 	c->tc_certdb = NULL; /* if not the default, may have to clean up */
592250e
-	PL_strfree( c->tc_certname );
592250e
-	c->tc_certname = NULL;
592250e
+	if ( c->tc_certdb_slot ) {
592250e
+		if ( SECMOD_CloseUserDB( c->tc_certdb_slot ) ) {
592250e
+			PRErrorCode errcode = PR_GetError();
592250e
+			Debug( LDAP_DEBUG_ANY,
592250e
+				   "TLS: could not close certdb slot - error %d:%s.\n",
592250e
+				   errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
592250e
+		}
592250e
+	}
592250e
 	PL_strfree( c->tc_pin_file );
592250e
 	c->tc_pin_file = NULL;
592250e
-	PL_strfree( c->tc_slotname );		
592250e
 	tlsm_free_pem_objs( c );
592250e
 #ifdef HAVE_NSS_INITCONTEXT
592250e
 	if ( c->tc_initctx ) {
592250e
-		LDAP_MUTEX_LOCK( &tlsm_init_mutex );
592250e
 		if ( NSS_ShutdownContext( c->tc_initctx ) ) {
592250e
 			PRErrorCode errcode = PR_GetError();
592250e
 			Debug( LDAP_DEBUG_ANY,
592250e
 				   "TLS: could not shutdown NSS - error %d:%s.\n",
592250e
 				   errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
592250e
  		}
592250e
-		LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
 	}
592250e
 	c->tc_initctx = NULL;
592250e
 #endif /* HAVE_NSS_INITCONTEXT */
592250e
+	LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
 #ifdef LDAP_R_COMPILE
592250e
 	ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
592250e
 #endif
592250e
@@ -2173,6 +2102,12 @@ tlsm_deferred_ctx_init( void *arg )
592250e
 		return -1;
592250e
 	}
592250e
 
592250e
+	if ( SSL_SetPKCS11PinArg(ctx->tc_model, ctx) ) {
592250e
+		Debug( LDAP_DEBUG_ANY,
592250e
+				"TLS: could not set pin prompt argument\n", 0, 0, 0);
592250e
+		return -1;
592250e
+	}
592250e
+
592250e
 	if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE ) ) {
592250e
 		Debug( LDAP_DEBUG_ANY,
592250e
 		       "TLS: could not set secure mode on.\n",
592250e
@@ -2287,14 +2222,30 @@ tlsm_deferred_ctx_init( void *arg )
592250e
 		/* if using the PEM module, load the PEM file specified by lt_certfile */
592250e
 		/* otherwise, assume this is the name of a cert already in the db */
592250e
 		if ( ctx->tc_using_pem ) {
592250e
-			/* this sets ctx->tc_certname to the correct value */
592250e
-			int rc = tlsm_add_cert_from_file( ctx, lt->lt_certfile, PR_FALSE, PR_TRUE );
592250e
+			/* this sets ctx->tc_certificate to the correct value */
592250e
+			int rc = tlsm_add_cert_from_file( ctx, lt->lt_certfile, PR_FALSE );
592250e
 			if ( rc ) {
592250e
 				return rc;
592250e
 			}
592250e
 		} else {
592250e
-			PL_strfree( ctx->tc_certname );
592250e
-			ctx->tc_certname = PL_strdup( lt->lt_certfile );
592250e
+			char *tmp_certname;
592250e
+
592250e
+			if (ctx->tc_certdb_slot) {
592250e
+				tmp_certname = PR_smprintf(TLSM_CERTDB_DESC_FMT ":%s", ctx->tc_unique, lt->lt_certfile);
592250e
+			} else {
592250e
+				tmp_certname = PR_smprintf("%s", lt->lt_certfile);
592250e
+			}
592250e
+
592250e
+			ctx->tc_certificate = PK11_FindCertFromNickname(tmp_certname, SSL_RevealPinArg(ctx->tc_model));
592250e
+			PR_smprintf_free(tmp_certname);
592250e
+
592250e
+			if (!ctx->tc_certificate) {
592250e
+				PRErrorCode errcode = PR_GetError();
592250e
+				Debug( LDAP_DEBUG_ANY,
592250e
+					   "TLS: error: the certificate '%s' could not be found in the database - error %d:%s.\n",
592250e
+					   lt->lt_certfile, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
592250e
+				return -1;
592250e
+			}
592250e
 		}
592250e
 	}
592250e
 
592250e
@@ -2302,7 +2253,6 @@ tlsm_deferred_ctx_init( void *arg )
592250e
 		/* if using the PEM module, load the PEM file specified by lt_keyfile */
592250e
 		/* otherwise, assume this is the pininfo for the key */
592250e
 		if ( ctx->tc_using_pem ) {
592250e
-			/* this sets ctx->tc_certname to the correct value */
592250e
 			int rc = tlsm_add_key_from_file( ctx, lt->lt_keyfile );
592250e
 			if ( rc ) {
592250e
 				return rc;
592250e
@@ -2334,66 +2284,42 @@ tlsm_deferred_ctx_init( void *arg )
592250e
 		/* 
592250e
 		   since a cert has been specified, assume the client wants to do cert auth
592250e
 		*/
592250e
-		if ( ctx->tc_certname ) {
592250e
-			if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
592250e
-				Debug( LDAP_DEBUG_ANY, 
592250e
-				       "TLS: error: unable to authenticate to the security device for certificate %s\n",
592250e
-				       ctx->tc_certname, 0, 0 );
592250e
-				return -1;
592250e
-			}
592250e
+		if ( ctx->tc_certificate ) {
592250e
 			if ( tlsm_clientauth_init( ctx ) ) {
592250e
 				Debug( LDAP_DEBUG_ANY, 
592250e
-				       "TLS: error: unable to set up client certificate authentication using %s\n",
592250e
-				       ctx->tc_certname, 0, 0 );
592250e
+				       "TLS: error: unable to set up client certificate authentication using '%s'\n",
592250e
+				       tlsm_ctx_subject_name(ctx), 0, 0 );
592250e
 				return -1;
592250e
 			}
592250e
 		}
592250e
 	} else { /* set up secure server */
592250e
 		SSLKEAType certKEA;
592250e
-		CERTCertificate *serverCert = NULL;
592250e
-		SECKEYPrivateKey *serverKey = NULL;
592250e
 		SECStatus status;
592250e
 
592250e
 		/* must have a certificate for the server to use */
592250e
-		if ( !ctx->tc_certname ) {
592250e
+		if ( !ctx->tc_certificate ) {
592250e
 			Debug( LDAP_DEBUG_ANY, 
592250e
 			       "TLS: error: no server certificate: must specify a certificate for the server to use\n",
592250e
 			       0, 0, 0 );
592250e
 			return -1;
592250e
 		}
592250e
 
592250e
-		/* authenticate to the server's token - this will do nothing
592250e
-		   if the key/cert db is not password protected */
592250e
-		if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
592250e
-			Debug( LDAP_DEBUG_ANY, 
592250e
-			       "TLS: error: unable to authenticate to the security device for certificate %s\n",
592250e
-			       ctx->tc_certname, 0, 0 );
592250e
-			return -1;
592250e
-		}
592250e
-
592250e
-		/* get the server's key and cert */
592250e
-		if ( tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, ctx->tc_is_server,
592250e
-						    &serverCert, &serverKey ) ) {
592250e
+		if (tlsm_find_and_verify_cert_key(ctx)) {
592250e
 			Debug( LDAP_DEBUG_ANY, 
592250e
 			       "TLS: error: unable to find and verify server's cert and key for certificate %s\n",
592250e
-			       ctx->tc_certname, 0, 0 );
592250e
-			CERT_DestroyCertificate( serverCert );
592250e
-			SECKEY_DestroyPrivateKey( serverKey );
592250e
+			       tlsm_ctx_subject_name(ctx), 0, 0 );
592250e
 			return -1;
592250e
 		}
592250e
 
592250e
-		certKEA = NSS_FindCertKEAType( serverCert );
592250e
 		/* configure the socket to be a secure server socket */
592250e
-		status = SSL_ConfigSecureServer( ctx->tc_model, serverCert, serverKey, certKEA );
592250e
-		/* SSL_ConfigSecureServer copies these */
592250e
-		CERT_DestroyCertificate( serverCert );
592250e
-		SECKEY_DestroyPrivateKey( serverKey );
592250e
+		certKEA = NSS_FindCertKEAType( ctx->tc_certificate );
592250e
+		status = SSL_ConfigSecureServer( ctx->tc_model, ctx->tc_certificate, ctx->tc_private_key, certKEA );
592250e
 
592250e
 		if ( SECSuccess != status ) {
592250e
 			PRErrorCode err = PR_GetError();
592250e
 			Debug( LDAP_DEBUG_ANY, 
592250e
-			       "TLS: error: unable to configure secure server using certificate %s - error %d:%s\n",
592250e
-			       ctx->tc_certname, err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) );
592250e
+			       "TLS: error: unable to configure secure server using certificate '%s' - error %d:%s\n",
592250e
+			       tlsm_ctx_subject_name(ctx), err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) );
592250e
 			return -1;
592250e
 		}
592250e
 	}
592250e
@@ -2515,7 +2441,9 @@ tlsm_session_new ( tls_ctx * ctx, int is_server )
592250e
 	int rc;
592250e
 
592250e
 	c->tc_is_server = is_server;
592250e
+	LDAP_MUTEX_LOCK( &tlsm_init_mutex );
592250e
 	status = PR_CallOnceWithArg( &c->tc_callonce, tlsm_deferred_ctx_init, c );
592250e
+	LDAP_MUTEX_UNLOCK( &tlsm_init_mutex );
592250e
 	if ( PR_SUCCESS != status ) {
592250e
 		PRErrorCode err = PR_GetError();
592250e
 		Debug( LDAP_DEBUG_ANY,