mrc0mmand / rpms / openldap

Forked from rpms/openldap 3 years ago
Clone

Blame SOURCES/openldap-tlsmc.patch

103552
MozNSS Interception Code
103552
103552
Author: Matus Honek <mhonek@redhat.com>
5ed10d
Date: Thu Jun 21 20:37:25 CEST 2018
103552
diff --git a/configure.in b/configure.in
103552
--- a/configure.in
103552
+++ b/configure.in
103552
@@ -237,6 +237,7 @@ dnl OL_ARG_ENABLE(referrals,[  --enable-referrals	  enable LDAPv2+ Referrals (ex
103552
 ol_enable_referrals=${ol_enable_referrals-no}
103552
 OL_ARG_ENABLE(ipv6,[  --enable-ipv6 	  enable IPv6 support], auto)dnl
103552
 OL_ARG_ENABLE(local,[  --enable-local	  enable AF_LOCAL (AF_UNIX) socket support], auto)dnl
103552
+OL_ARG_ENABLE(moznss_compatibility,[  --enable-moznss-compatibility	  enable MozNSS compatibility], no)dnl
103552
 
103552
 dnl ----------------------------------------------------------------
103552
 dnl General "with" options
103552
@@ -1256,6 +1257,26 @@ if test $ol_link_tls = no ; then
103552
 	fi
103552
 fi
103552
 
103552
+if test $ol_enable_moznss_compatibility = yes ; then
103552
+	if test $have_openssl = yes ; then
103552
+		if test $ol_with_tls = openssl ; then
103552
+			PKG_CHECK_MODULES(MOZNSS, [nss nspr], [have_moznss_libs=yes], [have_moznss_libs=no])
103552
+			if test $have_moznss_libs = yes ; then
103552
+				AC_DEFINE(HAVE_MOZNSS_COMPATIBILITY, 1,
103552
+					[define if you want to support MozNSS databases when compiled with OpenSSL])
103552
+				TLS_LIBS="$TLS_LIBS $MOZNSS_LIBS"
103552
+				CFLAGS="$CFLAGS $MOZNSS_CFLAGS"
103552
+			else
103552
+				AC_MSG_ERROR([For MOZNSS_COMPATIBILITY you have to have MozNSS present.])
103552
+			fi
103552
+		else
103552
+			AC_MSG_ERROR([For MOZNSS_COMPATIBILITY you have to compile with OpenSSL for crypto. (see --with-tls flag)])
103552
+		fi
103552
+	else
103552
+		AC_MSG_ERROR([For MOZNSS_COMPATIBILITY you have to have OpenSSL devel available. (unable to build with OpenSSL)])
103552
+	fi
103552
+fi
103552
+
103552
 WITH_TLS=no
103552
 if test $ol_link_tls = yes ; then
103552
 	AC_DEFINE(HAVE_TLS, 1, [define if you have TLS])
103552
diff --git a/doc/man/man3/ldap_get_option.3 b/doc/man/man3/ldap_get_option.3
103552
--- a/doc/man/man3/ldap_get_option.3
103552
+++ b/doc/man/man3/ldap_get_option.3
103552
@@ -772,6 +772,19 @@ must be
103552
 When using the OpenSSL library this is an SSL*. When using other
103552
 crypto libraries this is a pointer to an OpenLDAP private structure.
103552
 Applications generally should not use this option.
103552
+.TP
103552
+.B LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY
103552
+Sets/gets the status of the MozNSS database compatibility layer for TLS options. This options is available only if OpenLDAP is compiled with OpenSSL. This has effect only before the TLS context is established.
103552
+This option defaults to be on.
103552
+.BR invalue
103552
+should either be
103552
+.BR LDAP_OPT_OFF
103552
+or
103552
+.BR LDAP_OPT_ON ;
103552
+.BR outvalue
103552
+must be
103552
+.BR "int *" .
103552
+When set, just before TLS context initialization the library will first check if TLS settings are MozNSS-specific and if so it will export certificates from a preconfigured database and set other TLS settings so that OpenSSL can continue without issues.
103552
 .SH ERRORS
103552
 On success, the functions return
103552
 .BR LDAP_OPT_SUCCESS ,
103552
diff --git a/doc/man/man5/ldap.conf.5 b/doc/man/man5/ldap.conf.5
103552
--- a/doc/man/man5/ldap.conf.5
103552
+++ b/doc/man/man5/ldap.conf.5
103552
@@ -483,6 +483,11 @@ Check the CRL for a whole certificate chain
103552
 Specifies the file containing a Certificate Revocation List to be used
103552
 to verify if the server certificates have not been revoked. This
103552
 parameter is only supported with GnuTLS and Mozilla NSS.
103552
+.RE
103552
+.TP
103552
+.B TLS_MOZNSS_COMPATIBILITY <on/true/yes/off/false/no>
103552
+Specifies whether the MozNSS database compatibility layer for TLS options should be enabled. This options is available only if OpenLDAP is compiled with OpenSSL.
103552
+This option defaults to be on.
103552
 .SH "ENVIRONMENT VARIABLES"
103552
 .TP
103552
 LDAPNOINIT
103552
diff --git a/doc/man/man5/slapd-config.5 b/doc/man/man5/slapd-config.5
103552
--- a/doc/man/man5/slapd-config.5
103552
+++ b/doc/man/man5/slapd-config.5
103552
@@ -1004,6 +1004,11 @@ Check the CRL for a whole certificate chain
103552
 Specifies a file containing a Certificate Revocation List to be used
103552
 for verifying that certificates have not been revoked. This parameter
103552
 is only valid when using GnuTLS or Mozilla NSS.
103552
+.RE
103552
+.TP
103552
+.B olcTLSMozNSSCompatibility <on/true/yes/off/false/no>
103552
+Specifies whether the MozNSS database compatibility layer for TLS options should be enabled. This options is available only if OpenLDAP is compiled with OpenSSL.
103552
+This option defaults to be on.
103552
 .SH DYNAMIC MODULE OPTIONS
103552
 If
103552
 .B slapd
103552
diff --git a/doc/man/man5/slapd.conf.5 b/doc/man/man5/slapd.conf.5
103552
--- a/doc/man/man5/slapd.conf.5
103552
+++ b/doc/man/man5/slapd.conf.5
103552
@@ -1235,6 +1235,11 @@ Check the CRL for a whole certificate chain
103552
 Specifies a file containing a Certificate Revocation List to be used
103552
 for verifying that certificates have not been revoked. This directive is
103552
 only valid when using GnuTLS and Mozilla NSS.
103552
+.RE
103552
+.TP
103552
+.B TLSMozNSSCompatibility <on/true/yes/off/false/no>
103552
+Specifies whether the MozNSS database compatibility layer for TLS options should be enabled. This options is available only if OpenLDAP is compiled with OpenSSL.
103552
+This option defaults to be on.
103552
 .SH GENERAL BACKEND OPTIONS
103552
 Options in this section only apply to the configuration file section
103552
 for the specified backend.  They are supported by every
103552
diff --git a/include/ldap.h b/include/ldap.h
103552
--- a/include/ldap.h
103552
+++ b/include/ldap.h
103552
@@ -158,6 +158,10 @@ LDAP_BEGIN_DECL
103552
 #define LDAP_OPT_X_TLS_NEWCTX		0x600f
103552
 #define LDAP_OPT_X_TLS_CRLFILE		0x6010	/* GNUtls only */
103552
 #define LDAP_OPT_X_TLS_PACKAGE		0x6011
103552
+#define LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY  0x6050
103552
+
103552
+#define LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY_DISABLED	0
103552
+#define LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY_ENABLED	1
103552
 
103552
 #define LDAP_OPT_X_TLS_NEVER	0
103552
 #define LDAP_OPT_X_TLS_HARD		1
103552
diff --git a/libraries/libldap/Makefile.in b/libraries/libldap/Makefile.in
103552
--- a/libraries/libldap/Makefile.in
103552
+++ b/libraries/libldap/Makefile.in
103552
@@ -26,7 +26,7 @@ SRCS	= bind.c open.c result.c error.c compare.c search.c \
103552
 	request.c os-ip.c url.c pagectrl.c sortctrl.c vlvctrl.c \
103552
 	init.c options.c print.c string.c util-int.c schema.c \
103552
 	charray.c os-local.c dnssrv.c utf-8.c utf-8-conv.c \
103552
-	tls2.c tls_o.c tls_g.c tls_m.c \
103552
+	tls2.c tls_o.c tls_g.c tls_m.c tls_mc.c tls_mc_ossl.c \
103552
 	turn.c ppolicy.c dds.c txn.c ldap_sync.c stctrl.c \
103552
 	assertion.c deref.c ldif.c fetch.c
103552
 
103552
@@ -39,7 +39,7 @@ OBJS	= bind.lo open.lo result.lo error.lo compare.lo search.lo \
103552
 	request.lo os-ip.lo url.lo pagectrl.lo sortctrl.lo vlvctrl.lo \
103552
 	init.lo options.lo print.lo string.lo util-int.lo schema.lo \
103552
 	charray.lo os-local.lo dnssrv.lo utf-8.lo utf-8-conv.lo \
103552
-	tls2.lo tls_o.lo tls_g.lo tls_m.lo \
103552
+	tls2.lo tls_o.lo tls_g.lo tls_m.lo tls_mc.lo tls_mc_ossl.lo \
103552
 	turn.lo ppolicy.lo dds.lo txn.lo ldap_sync.lo stctrl.lo \
103552
 	assertion.lo deref.lo ldif.lo fetch.lo
103552
 
103552
diff --git a/libraries/libldap/init.c b/libraries/libldap/init.c
103552
--- a/libraries/libldap/init.c
103552
+++ b/libraries/libldap/init.c
103552
@@ -137,7 +137,9 @@ static const struct ol_attribute {
103552
 #ifdef HAVE_GNUTLS
103552
 	{0, ATTR_TLS,	"TLS_CRLFILE",			NULL,	LDAP_OPT_X_TLS_CRLFILE},
103552
 #endif
103552
-        
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+	{0, ATTR_TLS,   "TLS_MOZNSS_COMPATIBILITY",     NULL,   LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY},
103552
+#endif
103552
 #endif
103552
 
103552
 	{0, ATTR_NONE,		NULL,		NULL,	0}
103552
@@ -582,6 +584,9 @@ void ldap_int_initialize_global_options( struct ldapoptions *gopts, int *dbglvl
103552
 	gopts->ldo_tls_connect_cb = NULL;
103552
 	gopts->ldo_tls_connect_arg = NULL;
103552
 	gopts->ldo_tls_require_cert = LDAP_OPT_X_TLS_DEMAND;
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+	gopts->ldo_tls_moznss_compatibility = LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY_ENABLED;
103552
+#endif
103552
 #endif
103552
 	gopts->ldo_keepalive_probes = 0;
103552
 	gopts->ldo_keepalive_interval = 0;
103552
diff --git a/libraries/libldap/ldap-int.h b/libraries/libldap/ldap-int.h
103552
--- a/libraries/libldap/ldap-int.h
103552
+++ b/libraries/libldap/ldap-int.h
103552
@@ -260,7 +260,8 @@ struct ldapoptions {
103552
    	int			ldo_tls_require_cert;
103552
 	int			ldo_tls_impl;
103552
    	int			ldo_tls_crlcheck;
103552
-#define LDAP_LDO_TLS_NULLARG ,0,0,0,{0,0,0,0,0,0,0,0,0},0,0,0,0
103552
+   	int			ldo_tls_moznss_compatibility;
103552
+#define LDAP_LDO_TLS_NULLARG ,0,0,0,{0,0,0,0,0,0,0,0,0},0,0,0,0,0
103552
 #else
103552
 #define LDAP_LDO_TLS_NULLARG
103552
 #endif
103552
diff --git a/libraries/libldap/tls2.c b/libraries/libldap/tls2.c
103552
--- a/libraries/libldap/tls2.c
103552
+++ b/libraries/libldap/tls2.c
103552
@@ -37,6 +37,8 @@
103552
 
103552
 #include "ldap-tls.h"
103552
 
103552
+#include "tls_mc.h"
103552
+
103552
 static tls_impl *tls_imp = &ldap_int_tls_impl;
103552
 #define HAS_TLS( sb )	ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO, \
103552
 				(void *)tls_imp->ti_sbio )
103552
@@ -96,6 +98,7 @@ tls_ctx_ref( tls_ctx *ctx )
103552
  * an extra mutex for the default ctx.
103552
  */
103552
 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex;
103552
+ldap_pvt_thread_mutex_t tlsmc_mutex;
103552
 #endif
103552
 
103552
 void
103552
@@ -161,6 +164,7 @@ tls_init(tls_impl *impl )
103552
 	if ( !tls_initialized++ ) {
103552
 #ifdef LDAP_R_COMPILE
103552
 		ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex );
103552
+		ldap_pvt_thread_mutex_init( &tlsmc_mutex );
103552
 #endif
103552
 	}
103552
 
103552
@@ -196,6 +200,27 @@ ldap_int_tls_init_ctx( struct ldapoptions *lo, int is_server )
103552
 
103552
 	tls_init( ti );
103552
 
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+	if ( LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY_ENABLED == lo->ldo_tls_moznss_compatibility ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "TLSMC: MozNSS compatibility interception begins.\n",
103552
+		       0, 0, 0 );
103552
+		if ( 0 == tlsmc_intercept_initialization( lo, is_server ) ) {
103552
+			Debug( LDAP_DEBUG_TRACE,
103552
+			       "TLSMC: ERROR: MozNSS compatibility layer failed.\n",
103552
+			       0, 0, 0 );
103552
+		}
103552
+		lts = lo->ldo_tls_info;
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "TLSMC: MozNSS compatibility interception ends.\n",
103552
+		       0, 0, 0 );
103552
+	} else {
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "TLS: MozNSS compatibility layer disabled.\n",
103552
+		       0, 0, 0 );
103552
+	}
103552
+#endif
103552
+
103552
 	if ( is_server && !lts.lt_certfile && !lts.lt_keyfile &&
103552
 		!lts.lt_cacertfile && !lts.lt_cacertdir ) {
103552
 		/* minimum configuration not provided */
103552
@@ -572,6 +597,21 @@ ldap_int_tls_config( LDAP *ld, int option, const char *arg )
103552
 			return ldap_pvt_tls_set_option( ld, option, &i );
103552
 		}
103552
 		return -1;
103552
+#endif
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+	case LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY:
103552
+		i = -1;
103552
+		if ( (strcasecmp( arg, "yes" ) == 0) ||
103552
+		     (strcasecmp( arg, "true" ) == 0) ||
103552
+		     (strcasecmp( arg, "on" ) == 0) ) {
103552
+			i = LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY_ENABLED;
103552
+		}
103552
+		if ( (strcasecmp( arg, "no" ) == 0) ||
103552
+		     (strcasecmp( arg, "false" ) == 0) ||
103552
+		     (strcasecmp( arg, "off" ) == 0)  ) {
103552
+			i = LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY_DISABLED;
103552
+		}
103552
+		return ldap_pvt_tls_set_option( ld, option, &i );
103552
 #endif
103552
 	}
103552
 	return -1;
103552
@@ -675,6 +715,9 @@ ldap_pvt_tls_get_option( LDAP *ld, int option, void *arg )
103552
 	case LDAP_OPT_X_TLS_CONNECT_ARG:
103552
 		*(void **)arg = lo->ldo_tls_connect_arg;
103552
 		break;
103552
+	case LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY:
103552
+		*(int *)arg = lo->ldo_tls_moznss_compatibility;
103552
+		break;
103552
 	default:
103552
 		return -1;
103552
 	}
103552
@@ -802,6 +845,10 @@ ldap_pvt_tls_set_option( LDAP *ld, int option, void *arg )
103552
 			ldap_pvt_tls_ctx_free( lo->ldo_tls_ctx );
103552
 		lo->ldo_tls_ctx = NULL;
103552
 		return ldap_int_tls_init_ctx( lo, *(int *)arg );
103552
+	case LDAP_OPT_X_TLS_MOZNSS_COMPATIBILITY:
103552
+		if ( !arg ) return -1;
103552
+		lo->ldo_tls_moznss_compatibility = *(int *)arg;
103552
+		break;
103552
 	default:
103552
 		return -1;
103552
 	}
103552
diff --git a/libraries/libldap/tls_mc.c b/libraries/libldap/tls_mc.c
103552
new file mode 100644
103552
--- /dev/null
103552
+++ b/libraries/libldap/tls_mc.c
5ed10d
@@ -0,0 +1,1369 @@
103552
+#include "portable.h"
103552
+
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+
103552
+#include <sys/stat.h>
103552
+#include <sys/types.h>
103552
+#include <ac/unistd.h>
103552
+#include <ac/errno.h>
103552
+#include <ac/termios.h>
103552
+#include <fcntl.h>
103552
+#include <dirent.h>
103552
+
103552
+#include <nspr/nspr.h>
103552
+#include <nspr/private/pprio.h>
103552
+
103552
+#include <nss/nss.h>
103552
+#include <nss/pk11pub.h>
103552
+#include <nss/cert.h>
103552
+
103552
+#include <nss/base64.h>
103552
+#include <nss/key.h>
103552
+#include <nss/keyt.h>
103552
+#include <nss/blapi.h>
103552
+#include <nss/certdb.h>
103552
+
103552
+#include "ldap-int.h"
103552
+#include "ldap-tls.h"
103552
+#include "ldap_pvt_thread.h"
103552
+
103552
+#include "tls_mc.h"
103552
+#include "tls_mc_ossl.h"
103552
+
103552
+#define TLSMC_CHECKSUM_LEN 32
103552
+
103552
+#define TLSMC_CACERTS_DIR_NAME "cacerts"
103552
+#define TLSMC_CERT_FILE_NAME "cert.pem"
103552
+#define TLSMC_KEY_FILE_NAME "key.pem"
103552
+#define TLSMC_README_FILE_NAME "README"
103552
+
103552
+#define TLSM_CERTDB_DESC "ldap"
103552
+#define DEFAULT_TOKEN_NAME "default"
103552
+
103552
+#define TLSMC_IS_INPLACE 1
103552
+#define TLSMC_IS_TEMPORARY 2
103552
+
103552
+#define DONOTEDIT \
5ed10d
+	"This file is auto-generated by the MozNSS Compatibility Layer of OpenLDAP software.\n" \
5ed10d
+	"This layer is not part of the OpenLDAP software distributed in upstream.\n" \
5ed10d
+	"Please file any related bugs with your GNU/Linux distribution.\n" \
5ed10d
+	"Do not edit contents of this directory structure directly. Rather, change your configuration to use the OpenSSL-style TLS options, so that this directory structure does not need to be generated anymore.\n" \
5ed10d
+	"Please refer to the slapd.conf(5), slapd-config(5), and ldap.conf(5) man pages for more information."
103552
+#define PEM_CERT_HEADER "-----BEGIN CERTIFICATE-----"
103552
+#define PEM_CERT_FOOTER "-----END CERTIFICATE-----"
103552
+#define PEM_KEY_HEADER  "-----BEGIN PRIVATE KEY-----"
103552
+#define PEM_KEY_FOOTER "-----END PRIVATE KEY-----"
5ed10d
+#define README_HEADER "The contents of this file are hashed and used as part of the name of the parent directory.\n"
103552
+
103552
+#ifdef LDAP_R_COMPILE
103552
+ldap_pvt_thread_mutex_t tlsmc_mutex;
103552
+#endif
103552
+/*******************************************************************/
103552
+
103552
+
103552
+char *
103552
+tlsmc_path2name( char *path )
103552
+{
103552
+    if ( NULL == path ) return NULL;
103552
+    char *last_slash = strrchr( path, '/' );
103552
+    if ( NULL == last_slash )
103552
+        return path;
103552
+    else
103552
+        return last_slash + 1;
103552
+}
103552
+
103552
+
103552
+int
103552
+tlsmc_write_file( char *filename, char *buf, mode_t final_mode )
103552
+{
103552
+	int rv = 0;
103552
+	int fd = -1;
103552
+	if ( 0 > ( fd = open( filename, O_WRONLY | O_CREAT | O_EXCL, S_IWUSR ) ) ) {
5ed10d
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_write_file: ERROR: could not open file: `%s': %s.\n",
5ed10d
+		       filename, strerror(errno), 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( -1 >= write( fd, buf, strlen(buf) ) ) {
5ed10d
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_write_file: ERROR: could not write file: `%s': %s.\n",
5ed10d
+		       filename, strerror(errno), 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( -1 >= fchmod( fd, final_mode ) ) {
5ed10d
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_write_file: ERROR: could not set file mode: `%s': %s.\n",
5ed10d
+		       filename, strerror(errno), 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( -1 >= fsync( fd ) ) {
5ed10d
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_write_file: ERROR: could not fsync file: `%s': %s.\n",
5ed10d
+		       filename, strerror(errno), 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( 0 > close( fd ) ) {
5ed10d
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_write_file: ERROR: could not close file: `%s': %s.\n",
5ed10d
+		       filename, strerror(errno), 0 );
103552
+		fd = -1;
103552
+		goto bail;
103552
+	}
103552
+	fd = -1;
103552
+	rv = 1;
103552
+bail:
103552
+	if ( fd > -1 ) close( fd );
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+static int
103552
+tlsmc_remove_dir_recursively( const char *dir_name )
103552
+{
103552
+	int rv = 0;
103552
+	DIR *dir = NULL;
103552
+	struct dirent *entry = NULL;
103552
+	char *full_path = NULL;
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_remove_dir_recursively: INFO: starting recursively removing directory `%s'.\n",
103552
+	       dir_name, 0, 0 );
103552
+	if ( NULL == ( dir = opendir( dir_name ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_remove_dir_recursively: ERROR: could not open the directory (errno %d: %s).\n",
103552
+		       errno, strerror( errno ), 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	while ( NULL != ( entry = readdir( dir ) ) ) {
103552
+		struct stat info;
103552
+
103552
+		full_path = NULL;
103552
+		full_path = PR_smprintf( "%s/%s", dir_name, entry->d_name );
103552
+
103552
+		if ( 0 != strcmp( entry->d_name, "." ) && 0 != strcmp( entry->d_name, ".." ) ) {
103552
+			if ( 0 == lstat( full_path, &info ) ) {
103552
+				if ( S_ISDIR( info.st_mode ) ) {
103552
+					Debug( LDAP_DEBUG_TRACE,
103552
+					       "tlsmc_remove_dir_recursively: INFO: stepping into directory `%s'.\n",
103552
+					       entry->d_name, 0, 0 );
103552
+					if ( 0 == tlsmc_remove_dir_recursively( full_path ) ) {
103552
+						goto bail_and_close_dir;
103552
+					}
103552
+				} else {
103552
+					Debug( LDAP_DEBUG_TRACE,
103552
+					       "tlsmc_remove_dir_recursively: INFO: removing file `%s'.\n",
103552
+					       entry->d_name, 0, 0 );
103552
+					if ( 0 != remove( full_path ) ) {
103552
+						Debug( LDAP_DEBUG_ANY,
103552
+						       "tlsmc_remove_dir_recursively: ERROR: could not remove the file (errno %d: %s).\n",
103552
+						       errno, strerror( errno ), 0 );
103552
+						goto bail_and_close_dir;
103552
+					}
103552
+				}
103552
+			} else {
103552
+				Debug( LDAP_DEBUG_ANY,
103552
+				       "tlsmc_remove_dir_recursively: ERROR: could not stat `%s', (errno %d: %s).\n",
103552
+				       full_path, errno, strerror( errno ) );
103552
+				goto bail_and_close_dir;
103552
+			}
103552
+		}
103552
+
103552
+		if ( full_path ) {
103552
+			PR_smprintf_free( full_path );
103552
+			full_path = NULL;
103552
+		}
103552
+
103552
+	}
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_remove_dir_recursively: INFO: stepping out of the directory.\n",
103552
+	       0, 0, 0 );
103552
+	if ( 0 != closedir( dir ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_remove_dir_recursively: WARN: could not close the directory (errno %d: %s).\n",
103552
+		       errno, strerror( errno ), 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_remove_dir_recursively: INFO: removing the directory itself.\n",
103552
+	       0, 0, 0 );
103552
+	if ( 0 != remove( dir_name ) ) {
103552
+		PRErrorCode errcode = PR_GetError();
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_remove_dir_recursively: ERROR: could not remove the directory (errno %d: %s).\n",
103552
+		       errno, strerror( errno ), 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	rv = 1;
103552
+	goto bail;
103552
+bail_and_close_dir:
103552
+	closedir( dir );
103552
+bail:
103552
+	if ( full_path ) PR_smprintf_free( full_path );
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM tls_m.c */
103552
+static void
103552
+tlsmc_get_certdb_prefix( const char *certdir, char **nsscertdir, char **realcertdir, char **prefix )
103552
+{
103552
+	char sep = PR_GetDirectorySeparator();
103552
+	char *ptr = NULL;
103552
+	char *chkpath = NULL;
103552
+	struct PRFileInfo prfi;
103552
+	PRStatus prc;
103552
+
103552
+	*realcertdir = (char *)certdir; /* default is the one passed in */
103552
+
103552
+	/* if certdir is not given, just return */
103552
+	if ( !certdir ) return;
103552
+
103552
+	*nsscertdir = certdir;
103552
+
103552
+	/* ignore database type prefix (e.g. sql:, dbm:) if provided */
103552
+	if ( NULL != ( chkpath = strchr( certdir, ':' ) ) ) {
103552
+		*realcertdir = chkpath + 1;
103552
+	}
103552
+
103552
+	/* if certdir exists (file or directory) then it cannot specify a prefix */
103552
+	prc = PR_GetFileInfo( *realcertdir, &prfi );
103552
+	if ( prc == PR_SUCCESS ) {
103552
+		goto finish;
103552
+	}
103552
+
103552
+	/* if certdir was given, and there is a '/' in certdir, see if there
103552
+	   is anything after the last '/' - if so, assume it is the prefix */
103552
+	/* if ( ( ( ptr = strrchr( *realcertdir, sep ) ) ) && *(ptr + 1) ) { */
103552
+	/* 	*realcertdir = PL_strndup( *realcertdir, ptr - (*realcertdir) ); */
103552
+	/* 	*prefix = PL_strdup( ptr + 1 ); */
103552
+	/* } */
103552
+
103552
+
103552
+	if ( ptr = strrchr( *realcertdir, sep ) ) {
103552
+		if ( *(ptr + 1) ) {
103552
+			*ptr = '\0';
103552
+			*prefix = ptr + 1;
103552
+		} else {
103552
+			*prefix = *realcertdir + strlen( *realcertdir );  // empty string
103552
+		}
103552
+	} else {
103552
+		*prefix = *realcertdir;
103552
+		*realcertdir = *prefix + strlen( *prefix );  //  empty string
103552
+	}
103552
+finish:
103552
+	/* drop potential last '/' from realcertdir */
103552
+	do {
103552
+		ptr = strrchr( *realcertdir, sep );
103552
+		if ( ptr && (! *(ptr+1) ) ) {
103552
+			*ptr = '\0';
103552
+		} else {
103552
+			break;
103552
+		}
103552
+	} while (1);
103552
+
103552
+	return;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM tls_m.c */
103552
+static char *
103552
+tlsmc_get_pin_from_file(const char *token_name, char *filename)
103552
+{
103552
+	char *pwdstr = NULL;
103552
+	char *contents = NULL;
103552
+	char *lasts = NULL;
103552
+	char *line = NULL;
103552
+	char *candidate = NULL;
103552
+	PRFileInfo file_info;
103552
+	PRFileDesc *pwd_fileptr = NULL;
103552
+	pwd_fileptr = PR_Open( filename, PR_RDONLY, 00400 );
103552
+
103552
+	/* open the password file */
103552
+	if ( !pwd_fileptr ) {
103552
+		PRErrorCode errcode = PR_GetError();
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_get_pin_from_file: could not open security pin file %s - error %d:%s.\n",
103552
+		       filename, errcode,
103552
+		       PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
103552
+		goto done;
103552
+	}
103552
+
103552
+	/* get the file size */
103552
+	if ( PR_SUCCESS != PR_GetFileInfo( filename, &file_info ) ) {
103552
+		PRErrorCode errcode = PR_GetError();
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_get_pin_from_file: could not get file info from pin file %s - error %d:%s.\n",
103552
+		       filename, errcode,
103552
+		       PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
103552
+		goto done;
103552
+	}
103552
+
103552
+	/* create a buffer to hold the file contents */
103552
+	if ( !( contents = PR_CALLOC( file_info.size + 1 ) ) ) {
103552
+		PRErrorCode errcode = PR_GetError();
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_get_pin_from_file: could not alloc a buffer for contents of pin file %s - error %d:%s.\n",
103552
+		       filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
103552
+		goto done;
103552
+	}
103552
+
103552
+	/* read file into the buffer */
103552
+	if( PR_Read( pwd_fileptr, contents, file_info.size ) <= 0 ) {
103552
+		PRErrorCode errcode = PR_GetError();
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_get_pin_from_file: could not read the file contents from pin file %s - error %d:%s.\n",
103552
+		       filename, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
103552
+		goto done;
103552
+	}
103552
+
103552
+	/* format is [tokenname:]password EOL [tokenname:]password EOL ... */
103552
+	/* if you want to use a password containing a colon character, use
103552
+	   the special tokenname "default" */
103552
+	for ( line = PL_strtok_r( contents, "\r\n", &lasts ); line;
103552
+	      line = PL_strtok_r( NULL, "\r\n", &lasts ) ) {
103552
+		char *colon;
103552
+
103552
+		if ( !*line ) {
103552
+			continue; /* skip blank lines */
103552
+		}
103552
+		colon = PL_strchr( line, ':' );
103552
+		if ( colon ) {
103552
+			if ( *(colon + 1) && token_name &&
103552
+			     !PL_strncmp( token_name, line, colon-line ) ) {
103552
+				candidate = colon + 1; /* found a definite match */
103552
+				break;
103552
+			} else if ( !PL_strncmp( DEFAULT_TOKEN_NAME, line, colon-line ) ) {
103552
+				candidate = colon + 1; /* found possible match */
103552
+			}
103552
+		} else { /* no token name */
103552
+			candidate = line;
103552
+		}
103552
+	}
103552
+done:
103552
+	if ( pwd_fileptr ) {
103552
+		PR_Close( pwd_fileptr );
103552
+	}
103552
+	if ( candidate ) {
103552
+		pwdstr = PL_strdup( candidate );
103552
+	}
103552
+	PL_strfree( contents );
103552
+
103552
+	return pwdstr;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM tls_m.c */
103552
+/*
103552
+ * Turn the echoing off on a tty.
103552
+ */
103552
+static void
103552
+echoOff(int fd)
103552
+{
103552
+	if ( isatty( fd ) ) {
103552
+		struct termios tio;
103552
+		tcgetattr( fd, &tio );
103552
+		tio.c_lflag &= ~ECHO;
103552
+		tcsetattr( fd, TCSAFLUSH, &tio );
103552
+	}
103552
+}
103552
+
103552
+/* BORROWED FROM tls_m.c */
103552
+/*
103552
+ * Turn the echoing on on a tty.
103552
+ */
103552
+static void
103552
+echoOn(int fd)
103552
+{
103552
+	if ( isatty( fd ) ) {
103552
+		struct termios tio;
103552
+		tcgetattr( fd, &tio );
103552
+		tio.c_lflag |= ECHO;
103552
+		tcsetattr( fd, TCSAFLUSH, &tio );
103552
+		tcsetattr( fd, TCSAFLUSH, &tio );
103552
+	}
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM tls_m.c */
103552
+char *
103552
+tlsmc_get_pin( PK11SlotInfo *slot, PRBool retry, void * filename)
103552
+{
103552
+	char *token_name = NULL;
103552
+	char *pwdstr = NULL;
103552
+
103552
+	token_name = PK11_GetTokenName( slot );
103552
+	/* Try to get the passwords from the password file if it exists.
103552
+	 * THIS IS UNSAFE and is provided for convenience only. Without this
103552
+	 * capability the server would have to be started in foreground mode
103552
+	 * if using an encrypted key.
103552
+	 */
103552
+	if ( filename ) {
103552
+		fprintf( stderr,
103552
+		         "tlsmc_get_pin: INFO: Please note the extracted key file will not be protected with a PIN any more, however it will be still protected at least by file permissions.\n");
103552
+		pwdstr = tlsmc_get_pin_from_file( token_name, (char *)filename );
103552
+		if ( retry && pwdstr != NULL )
103552
+			return NULL;
103552
+	}
103552
+	if ( !pwdstr ) {
103552
+		int infd = PR_FileDesc2NativeHandle( PR_STDIN );
103552
+		int isTTY = isatty( infd );
103552
+		unsigned char phrase[200];
103552
+		/* Prompt for password */
103552
+		if ( isTTY ) {
103552
+			fprintf( stderr,
103552
+			         "tlsmc_get_pin: INFO: Please note the extracted key file will not be protected with a PIN any more, however it will be still protected at least by file permissions.\n");
103552
+			fprintf( stdout,
103552
+				 "Please enter pin, password, or pass phrase for security token '%s': ",
103552
+				 token_name ? token_name : DEFAULT_TOKEN_NAME );
103552
+			echoOff( infd );
103552
+		}
103552
+		fgets( (char*)phrase, sizeof(phrase), stdin );
103552
+		if ( isTTY ) {
103552
+			fprintf( stdout, "\n" );
103552
+			echoOn( infd );
103552
+		}
103552
+		/* stomp on newline */
103552
+		phrase[strlen((char*)phrase)-1] = 0;
103552
+
103552
+		pwdstr = PL_strdup( (char*)phrase );
103552
+	}
103552
+
103552
+	return pwdstr;
103552
+}
103552
+
103552
+
103552
+int
103552
+tlsmc_hash( char **dest, const char *src )
103552
+{
103552
+	int rv = 0;
103552
+	unsigned char fp[SHA256_LENGTH];
103552
+	SECItem fpItem;
103552
+
103552
+	if ( SECSuccess != ( rv = PK11_HashBuf( SEC_OID_SHA256, fp, src, strlen(src) ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_hash: could not hash a buffer",
103552
+		       NULL, NULL, NULL );
103552
+		goto bail;
103552
+	}
103552
+	fpItem.data = fp;
103552
+	fpItem.len = SHA256_LENGTH;
103552
+	if ( NULL == ( *dest = CERT_Hexify( &fpItem, 0 ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_hash: could not hexify the hash",
103552
+		       NULL, NULL, NULL );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	rv = 1;
103552
+bail:
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM tls_m.c */
103552
+int
103552
+tlsmc_open_nssdb( char *ld_cacertdir, NSSInitContext **out_initctx, char **out_nssdb_dir, char **out_nssdb_prefix )
103552
+{
103552
+#define SECURITYDIRS_COUNT 3
103552
+	int rc = 0;
103552
+	PRErrorCode errcode = 1;
103552
+
103552
+	/* restart secmod modules */
103552
+#ifdef HAVE_SECMOD_RESTARTMODULES
103552
+	/* NSS enforces the pkcs11 requirement that modules should be unloaded after
103552
+	   a fork() - since there is no portable way to determine if NSS has been
103552
+	   already initialized in a parent process, we just call SECMOD_RestartModules
103552
+	   with force == FALSE - if the module has been unloaded due to a fork, it will
103552
+	   be reloaded, otherwise, it is a no-op */
103552
+	if ( 0 == ( rc = SECMOD_RestartModules(PR_FALSE /* do not force */) ) ) {
103552
+		errcode = PORT_GetError();
103552
+		if ( errcode != SEC_ERROR_NOT_INITIALIZED ) {
103552
+			Debug( LDAP_DEBUG_TRACE,
103552
+			       "tlsmc_open_nssdb: WARN: could not restart the security modules: %d:%s.\n",
103552
+			       errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
103552
+		} else {
103552
+			errcode = 1;
103552
+		}
103552
+	}
103552
+#endif
103552
+
103552
+
103552
+	/* context and certdb */
103552
+	char *dir_moznss = PR_GetEnv( "MOZNSS_DIR" );
103552
+	char *dir_default_moznss = PR_GetEnv( "DEFAULT_MOZNSS_DIR" );
103552
+	const char *securitydirs[SECURITYDIRS_COUNT] = { dir_moznss, ld_cacertdir, dir_default_moznss };
103552
+	int done = 0;
103552
+	int ii = 0;
103552
+	for ( ii = 0; !done && ( ii < SECURITYDIRS_COUNT ); ++ii ) {
103552
+		// get certdb prefix
103552
+		const char *securitydir = securitydirs[ii];
103552
+		char *nsscertdir = NULL;
103552
+		char *realcertdir = NULL;
103552
+		const char *defprefix = "";
103552
+		char *prefix = (char *)defprefix;
103552
+		if ( securitydir == NULL ) continue;
103552
+		tlsmc_get_certdb_prefix( securitydir, &nsscertdir, &realcertdir, &prefix );
103552
+		*out_nssdb_dir = strdup( realcertdir );
103552
+		*out_nssdb_prefix = strdup( prefix );
103552
+
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_open_nssdb: INFO: trying to initialize moznss using security dir `%s` prefix `%s`.\n",
103552
+		       nsscertdir, prefix, NULL);
103552
+
103552
+		// init context
103552
+		NSSInitContext *initctx = NULL;
103552
+		NSSInitParameters initparams;
103552
+		memset( &initparams, 0, sizeof( initparams ) );
103552
+		initparams.length = sizeof( initparams );
103552
+
103552
+		initctx = NSS_InitContext( nsscertdir,
103552
+		                           prefix,
103552
+		                           prefix,
103552
+		                           SECMOD_DB,
103552
+		                           &initparams,
103552
+		                           NSS_INIT_READONLY // | NSS_INIT_NOCERTDB
103552
+			);
103552
+		rc = initctx ? 1 : 0;
103552
+
103552
+		*out_initctx = initctx;
103552
+
103552
+		if ( rc != 1 ) {
103552
+			errcode = PORT_GetError();
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_open_nssdb: WARN: could not initialize MozNSS context - error %d.\n",
103552
+			       errcode, 0, 0 );
103552
+		} else {
103552
+			Debug( LDAP_DEBUG_TRACE,
103552
+			       "tlsmc_open_nssdb: INFO: initialized MozNSS context.\n",
103552
+			       0, 0, 0 );
103552
+			errcode = 0;
103552
+			done = 1;
103552
+		}
103552
+	}
103552
+
103552
+	PR_Free( dir_moznss );
103552
+	PR_Free( dir_default_moznss );
103552
+
103552
+	PK11_SetPasswordFunc( tlsmc_get_pin );
103552
+
103552
+	if ( done && (errcode == 0) && out_initctx ) {
103552
+		return 1;
103552
+	} else {
103552
+		return 0;
103552
+	}
103552
+}
103552
+
103552
+
103552
+int
103552
+tlsmc_filestamp( char **filestamp, char *path )
103552
+{
103552
+	int rv = 0;
103552
+	struct stat attr;
103552
+	char stime[20];
103552
+
103552
+	if ( 0 != stat( path, &attr ) ) {
103552
+		rv = -1;
103552
+		goto bail;
103552
+	}
103552
+	if ( 0 == strftime(stime, sizeof(stime), "%FT%T", localtime(&attr.st_mtime)) ) {
5ed10d
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_filestamp: ERROR: could not format mtime: %s.\n",
5ed10d
+		       strerror(errno), 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	*filestamp = PR_smprintf("mtime %s.%d, size %lld",
103552
+	                         stime, attr.st_mtim.tv_nsec, (long long) attr.st_size);
103552
+
103552
+	rv = 1;
103552
+bail:
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+char *
103552
+tlsmc_compute_checksum( char *nssdb_dir, char *nssdb_prefix,
103552
+                        char *ld_cacertdir, char *ld_cert, char *ld_key,
103552
+                        char **out_data)
103552
+{
103552
+	int rv = 0;
103552
+	char *data = NULL;
103552
+	char *checksum = NULL;
103552
+
103552
+	/* gather data */
103552
+	data = PR_sprintf_append( data,
103552
+	                          DONOTEDIT "\n"
103552
+	                          README_HEADER "\n"
103552
+	                          "PARAMETERS:\n"
103552
+	                          "nssdb_dir: %s\n"
103552
+	                          "nssdb_prefix: %s\n"
103552
+	                          "ld_cacertdir: %s\n"
103552
+	                          "ld_cert: %s\n"
103552
+	                          "ld_key: %s\n"
103552
+	                          "euid: %d\n\n"
103552
+	                          "FILES:\n",
103552
+	                          nssdb_dir, nssdb_prefix, ld_cacertdir, ld_cert, ld_key, geteuid() );
103552
+
103552
+	char *files[] = { "cert8.db", "cert9.db", "key3.db", "key4.db", "secmod.db", NULL };
103552
+	char **filep = NULL;
103552
+	for ( filep = files; NULL != *filep; filep++ ) {
103552
+		char *filestamp = NULL;
103552
+		char *path = NULL;
103552
+		path = PR_smprintf( "%s/%s%s", nssdb_dir, nssdb_prefix, *filep );
103552
+		if ( 0 == tlsmc_filestamp( &filestamp, path ) ) {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_compute_checksum: INFO: could not check file `%s'.\n",
103552
+			       path, 0, 0 );
103552
+			rv = -1;
103552
+		} else {
103552
+			data = PR_sprintf_append( data, "%s: %s\n", *filep, filestamp );
103552
+		}
103552
+		if ( filestamp ) PR_smprintf_free( filestamp );
103552
+		if ( path ) PR_smprintf_free( path );
103552
+		if ( -1 == rv ) goto bail;
103552
+	}
103552
+
103552
+	/* compute data checksum */
103552
+	if ( 1 != tlsmc_hash( &checksum, (const char*) data ) ) {
103552
+		checksum = NULL;
103552
+		goto bail;
103552
+	}
103552
+
103552
+	/* possibly supply data */
103552
+	if ( out_data ) {
103552
+		*out_data = strdup( data );
103552
+	}
103552
+
103552
+	/* return checksum */
103552
+bail:
103552
+	if ( data ) PR_smprintf_free( data );
103552
+	return checksum;
103552
+}
103552
+
103552
+
103552
+int
103552
+tlsmc_prepare_dir( char *dir )
103552
+{
103552
+	int rv = 0;
103552
+	char *cacerts_dir = NULL;
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_prepare_dir: INFO: preparing PEM directory `%s'.\n",
103552
+	       dir, 0, 0 );
103552
+
103552
+	if ( 0 != mkdir( dir, S_IRWXU /* u+rwx */ ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_prepare_dir: WARN: could not create the PEM directory.\n",
103552
+		       0, 0, 0 );
103552
+		rv = 0;
103552
+		goto bail;
103552
+	}
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_prepare_dir: INFO: creating a subdirectory `%s'.\n",
103552
+	       TLSMC_CACERTS_DIR_NAME, 0, 0 );
103552
+	cacerts_dir = PR_smprintf( "%s/%s", dir, TLSMC_CACERTS_DIR_NAME );
103552
+	if ( 0 != mkdir( cacerts_dir, S_IRWXU /* u+rwx */ ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
5ed10d
+		       "tlsmc_prepare_dir: WARN: could not create the subdirectory.\n",
103552
+		       0, 0, 0 );
103552
+		rv = 0;
103552
+		goto bail;
103552
+	}
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_prepare_dir: INFO: successfully created PEM directory structure.\n",
103552
+	       TLSMC_CACERTS_DIR_NAME, 0, 0 );
103552
+	rv = 1;
103552
+
103552
+bail:
103552
+	if ( cacerts_dir ) PR_smprintf_free( cacerts_dir );
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM 389ds: ssl.c */
103552
+int
103552
+tlsmc_extract_cert_to_file(CERTCertDBHandle *certdb_handle, CERTCertificate *cert, char *file_path)
103552
+{
103552
+	int rv = 0;
103552
+	SECItem data;
103552
+	char *b64 = NULL;
103552
+	char *output = NULL;
103552
+
103552
+	if ( ! cert ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_cert_to_file: ERROR: cert empty.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	data.data = cert->derCert.data;
103552
+	data.len = cert->derCert.len;
103552
+	b64 = BTOA_DataToAscii(data.data, data.len);
103552
+	if ( ! b64 ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_cert_to_file: ERROR: could not base64 encode.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	output = PR_smprintf( DONOTEDIT "\n\n"
103552
+	                      "NSS nickname: %s\n"
103552
+	                      "Issuer: %s\n"
103552
+	                      "Subject: %s\n"
103552
+	                      PEM_CERT_HEADER "\n"
103552
+	                      "%s\n"
103552
+	                      PEM_CERT_FOOTER "\n",
103552
+	                      cert->nickname,
103552
+	                      cert->issuerName,
103552
+	                      cert->subjectName,
103552
+	                      b64 );
103552
+
103552
+	if ( 0 == tlsmc_write_file( file_path, output, S_IRUSR ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_cert_to_file: ERROR: could not write certificate.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	rv = 1;
103552
+bail:
103552
+	if ( output ) PR_smprintf_free( output );
103552
+	if ( b64 ) PORT_Free( b64 );
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM 389ds: ssl.c */
103552
+int
103552
+tlsmc_decrypt_key(SECKEYEncryptedPrivateKeyInfo *epki,
103552
+                  SECOidTag algTag,
103552
+                  SECItem *pwitem,
103552
+                  void *pin_arg,
103552
+                  SECItem *derPKI)
103552
+{
103552
+	SECItem  *cryptoParam = NULL;
103552
+	PK11SymKey *symKey = NULL;
103552
+	PK11Context *ctx = NULL;
103552
+	int rv = 0;
103552
+
103552
+	if (!pwitem) return rv;
103552
+
103552
+	do {
103552
+		SECAlgorithmID algid = epki->algorithm;
103552
+		CK_MECHANISM_TYPE cryptoMechType;
103552
+		CK_ATTRIBUTE_TYPE operation = CKA_DECRYPT;
103552
+		PK11SlotInfo *slot = NULL;
103552
+
103552
+		cryptoMechType = PK11_GetPBECryptoMechanism(&algid, &cryptoParam, pwitem);
103552
+		if (cryptoMechType == CKM_INVALID_MECHANISM)  {
103552
+			goto bail;
103552
+		}
103552
+
103552
+		if ( NULL == ( slot = PK11_GetBestSlot(cryptoMechType, NULL) ) ) {
103552
+			goto bail;
103552
+		}
103552
+
103552
+		if ( NULL == ( symKey = PK11_PBEKeyGen(slot, &algid, pwitem, PR_FALSE, pin_arg) ) ) {
103552
+			rv = -1;
103552
+			goto bail_one;
103552
+		}
103552
+
103552
+		if ( NULL == ( ctx = PK11_CreateContextBySymKey(
103552
+			               cryptoMechType, operation, symKey, cryptoParam) ) ) {
103552
+			rv = -1;
103552
+			goto bail_one;
103552
+		}
103552
+
103552
+		if ( SECSuccess != PK11_CipherOp(ctx,
103552
+		                                 derPKI->data, /* out */
103552
+		                                 (int *)(&derPKI->len), /* out len */
103552
+		                                 (int)epki->encryptedData.len, /* max out */
103552
+		                                 epki->encryptedData.data,      /* in */
103552
+		                                 (int)epki->encryptedData.len /* in len */ ) ) {
103552
+			rv = -1;
103552
+			goto bail_one;
103552
+		}
103552
+
103552
+		if ( derPKI->len != epki->encryptedData.len ) goto bail_one;
103552
+		if ( SECSuccess != PK11_Finalize(ctx) ) goto bail_one;
103552
+	bail_one:
103552
+		if (slot) PK11_FreeSlot(slot);
103552
+	} while (0);
103552
+
103552
+	rv = ((rv == 0) ? 1 : 0);
103552
+bail:
103552
+	if (symKey) PK11_FreeSymKey(symKey);
103552
+	if (cryptoParam) {
103552
+		SECITEM_ZfreeItem(cryptoParam, PR_TRUE);
103552
+		cryptoParam = NULL;
103552
+	}
103552
+	if (ctx) PK11_DestroyContext(ctx, PR_TRUE);
103552
+
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM 389ds: ssl.c */
103552
+int
103552
+tlsmc_extract_key_of_cert_to_file(CERTCertificate *cert,
103552
+                                  char *pin_filename,
103552
+                                  char *filename)
103552
+{
103552
+	int rv = 0;
103552
+	SECKEYPrivateKey *key = NULL;
103552
+	SECItem pwitem;
103552
+	SECKEYEncryptedPrivateKeyInfo *epki = NULL;
103552
+	PLArenaPool *arenaForPKI = NULL;
103552
+	SECItem clearKeyDER;
103552
+	char *b64 = NULL;
103552
+	char *output = NULL;
103552
+
103552
+	// establish password
103552
+	pwitem.data = "secretpw";  // FIXME use pin_filename
103552
+	pwitem.len = strlen(pwitem.data);
103552
+	pwitem.type = siBuffer;
103552
+
103552
+	// get key
103552
+	if ( NULL == ( key = PK11_FindKeyByAnyCert(cert, (void *)pin_filename) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_key_of_cert_to_file: ERROR: PK11_FindKeyByAnyCert failed.\n",
103552
+		       0,0,0);
103552
+		goto bail;
103552
+	}
103552
+
103552
+	// get key info
103552
+	if ( NULL == ( epki = PK11_ExportEncryptedPrivKeyInfo(
103552
+		               NULL, SEC_OID_DES_EDE3_CBC, &pwitem, key, 1000, (void *)pin_filename) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_key_of_cert_to_file: ERROR: PK11_ExportEncryptedPrivKeyInfo returned NULL.\n",
103552
+		       0,0,0);
103552
+		goto bail;
103552
+	}
103552
+
103552
+	// get clear DER
103552
+	if ( NULL == ( arenaForPKI = PORT_NewArena(2048) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_key_of_cert_to_file: ERROR: PORT_NewArena failed.\n",
103552
+		       0,0,0);
103552
+		goto bail;
103552
+	}
103552
+
103552
+	clearKeyDER.data = PORT_ArenaAlloc(arenaForPKI, epki->encryptedData.len);
103552
+	clearKeyDER.len = epki->encryptedData.len;
103552
+	clearKeyDER.type = siBuffer;
103552
+
103552
+	if ( 0 == tlsmc_decrypt_key(epki, SEC_OID_DES_EDE3_CBC, &pwitem,
103552
+	                                     (void *)pin_filename, &clearKeyDER) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_key_of_cert_to_file: ERROR: could not decrypt the key.\n",
103552
+		       0,0,0);
103552
+		goto bail;
103552
+	}
103552
+
103552
+	// base64 encode
103552
+	if ( NULL == ( b64 = BTOA_ConvertItemToAscii(&clearKeyDER) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_key_of_cert_to_file: ERROR: could not base64 encode.\n",
103552
+		       0,0,0);
103552
+		goto bail;
103552
+	}
103552
+
103552
+	// print out
103552
+	output = PR_smprintf( DONOTEDIT "\n"
103552
+	                      PEM_KEY_HEADER "\n"
103552
+	                      "%s\n"
103552
+	                      PEM_KEY_FOOTER "\n",
103552
+	                      b64 );
103552
+
103552
+	if ( 0 == tlsmc_write_file( filename, output, S_IRUSR ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_key_of_cert_to_file: ERROR: could not write PK.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	rv = 1;
103552
+
103552
+bail:
103552
+	if (b64) PORT_Free(b64);
103552
+	if (arenaForPKI) PORT_FreeArena(arenaForPKI, PR_FALSE);
103552
+	if (epki) SECKEY_DestroyEncryptedPrivateKeyInfo(epki, PR_TRUE);
103552
+	if (key) SECKEY_DestroyPrivateKey(key);
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM 389ds: ssl.c */
103552
+int
103552
+tlsmc_extract_cert_key_pair(char *nickname, char *pin_filename, char *dir_name)
103552
+{
103552
+	int rv = 0;
103552
+	CERTCertDBHandle *certHandle = NULL;
103552
+	CERTCertificate *cert = NULL;
103552
+	char *cert_file_path = NULL;
103552
+	char *key_file_path = NULL;
103552
+	char *file_realpath = NULL;
103552
+
103552
+
103552
+	cert_file_path = PR_smprintf( "%s/cert.pem", dir_name );
103552
+	key_file_path = PR_smprintf( "%s/key.pem", dir_name );
103552
+
103552
+	if ( NULL == nickname ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_cert_key_pair: WARN: supplied nickname is empty (NULL).\n",
103552
+		       0, 0, 0 );
103552
+		rv = 1;
103552
+		goto bail;
103552
+	}
103552
+	if ( NULL == ( certHandle = CERT_GetDefaultCertDB() ) ) {
103552
+		// FIXME see same in tlsmc_extract_cacerts()
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_cert_key_pair: ERROR: could not get certificate handle.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( NULL != ( cert = PK11_FindCertFromNickname(nickname, NULL) ) ) {
103552
+		/* extract cert/key from NSS db */
103552
+
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_extract_cert_key_pair: INFO: extracting certificate `%s' to file `%s'.\n",
103552
+		       nickname, cert_file_path, 0 );
103552
+		if ( 0 == tlsmc_extract_cert_to_file(certHandle, cert, cert_file_path) ) {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_extract_cert_key_pair: ERROR: could not extract certificate.\n",
103552
+			       0, 0, 0 );
103552
+			goto bail;
103552
+		}
103552
+
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_extract_cert_key_pair: INFO: extracting associated PK to file `%s'.\n",
103552
+		       key_file_path, 0, 0 );
103552
+		if ( 0 == tlsmc_extract_key_of_cert_to_file( cert, pin_filename, key_file_path ) ) {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_extract_cert_key_pair: ERROR: could not extract PK.\n",
103552
+			       0, 0, 0 );
103552
+			goto bail;
103552
+		}
103552
+	} else {
103552
+		/* symlink PEM cert/key PEM files */
103552
+
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_cert_key_pair: INFO: could not find certificate with nickname `%s', expecting a PEM file.\n",
103552
+		       nickname, 0, 0 );
103552
+
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_extract_cert_key_pair: INFO: symlinking certificate file `%s' to file `%s'.\n",
103552
+		       nickname, cert_file_path, 0 );
103552
+		if ( NULL == ( file_realpath = realpath( nickname, NULL ) ) ) {
5ed10d
+			Debug( LDAP_DEBUG_ANY,
5ed10d
+			       "tlsmc_extract_cert_key_pair: ERROR: could not get realpath of certificate file `%s'.\n",
5ed10d
+			       nickname, 0, 0 );
103552
+			goto bail;
103552
+		}
103552
+		if ( -1 == symlink( file_realpath, cert_file_path ) ) {
5ed10d
+			Debug( LDAP_DEBUG_ANY,
5ed10d
+			       "tlsmc_extract_cert_key_pair: ERROR: could not create a symlink of `%s' to `%s'.\n",
5ed10d
+			       file_realpath, cert_file_path, 0 );
103552
+			goto bail;
103552
+		}
103552
+		if ( file_realpath ) free( file_realpath );
103552
+
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_extract_cert_key_pair: INFO: symlinking PK file `%s' to file `%s'.\n",
103552
+		       pin_filename, key_file_path, 0 );
103552
+		if ( NULL == ( file_realpath = realpath( pin_filename, NULL ) ) ) {
5ed10d
+			Debug( LDAP_DEBUG_ANY,
5ed10d
+			       "tlsmc_extract_cert_key_pair: ERROR: could not get realpath of PK file `%s'.\n",
5ed10d
+			       pin_filename, 0, 0 );
103552
+			goto bail;
103552
+		}
103552
+		if ( -1 == symlink( file_realpath, key_file_path ) ) {
5ed10d
+			Debug( LDAP_DEBUG_ANY,
5ed10d
+			       "tlsmc_extract_cert_key_pair: ERROR: could not create a symlink of `%s' to `%s'.\n",
5ed10d
+			       file_realpath, key_file_path, 0 );
103552
+			goto bail;
103552
+		}
103552
+	}
103552
+
103552
+	rv = 1;
103552
+
103552
+bail:
103552
+	if (file_realpath) free(file_realpath);
103552
+	if (key_file_path) PR_smprintf_free(key_file_path);
103552
+	if (cert_file_path) PR_smprintf_free(cert_file_path);
103552
+	if (cert) CERT_DestroyCertificate(cert);
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM 389ds: ssl.c */
103552
+int
103552
+tlsmc_extract_cacerts( char *dir_name )
103552
+{
103552
+	int rv = 0;
103552
+	CERTCertDBHandle *certHandle = NULL;
103552
+	CERTCertListNode *node = NULL;
103552
+	CERTCertList *list = NULL;
103552
+	char *cacerts_dir = NULL;
103552
+	int cert_cnt = 0;
103552
+
103552
+	cacerts_dir = PR_smprintf( "%s/" TLSMC_CACERTS_DIR_NAME, dir_name );
103552
+
103552
+	certHandle = CERT_GetDefaultCertDB();  // FIXME maybe we should really use certdb_slot?
103552
+	if ( ! certHandle ) {
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_extract_cacerts: could not get certificate database handle.\n",
103552
+		       0, 0, 0);
103552
+		goto bail;
103552
+	}
103552
+
103552
+	list = PK11_ListCerts(PK11CertListAll, NULL);
103552
+	if ( ! list ) {
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_extract_cacerts: could not get list of certificates.\n",
103552
+		       0, 0, 0);
103552
+		goto bail;
103552
+	}
103552
+	for ( node = CERT_LIST_HEAD(list);
103552
+	      !CERT_LIST_END(node, list);
103552
+	      node = CERT_LIST_NEXT(node)) {
103552
+
103552
+		CERTCertificate *cert = NULL;
103552
+		CERTCertTrust trust;
103552
+		char *cert_file_path = NULL;
103552
+		int is_ca = 0;
103552
+
103552
+		cert = node->cert;
103552
+		if ( SECFailure == CERT_GetCertTrust( cert, &trust ) ) {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_extract_cacerts: ERROR: could not get trust flags of certificate nick=`%s'.\n",
103552
+			       cert->nickname, 0, 0);
103552
+			goto bail;
103552
+		}
103552
+		if (trust.sslFlags &
103552
+		    (CERTDB_VALID_CA | CERTDB_TRUSTED_CA | CERTDB_TRUSTED_CLIENT_CA)) {
103552
+			is_ca = 1;
103552
+		}
103552
+
103552
+		Debug(LDAP_DEBUG_TRACE,
103552
+		      "tlsmc_extract_cacerts: INFO: found cert nick=`%s'%s.\n",
103552
+		      cert->nickname, is_ca ? ", a trusted CA" : ", _not_ a trusted CA, skipping", 0);
103552
+		if ( ! is_ca ) continue;
103552
+
103552
+		cert_file_path = PR_smprintf( "%s/cert%d.pem", cacerts_dir, cert_cnt );
103552
+		cert_cnt++;
103552
+		Debug(LDAP_DEBUG_TRACE,
103552
+		      "tlsmc_extract_cacerts: INFO: extracting cert nick=`%s' to file `%s'.\n",
103552
+		      cert->nickname, cert_file_path, 0);
103552
+		if ( 0 == tlsmc_extract_cert_to_file( certHandle, cert, cert_file_path ) ) {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_extract_cacerts: ERROR: could not extract the certificate.\n",
103552
+			       0, 0, 0);
103552
+			goto bail_one;
103552
+		}
103552
+		if ( 0 == tlsmc_cert_create_hash_symlink( cert_file_path, cacerts_dir ) ) {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_extract_cacerts: ERROR: could not rehash the certificate.\n",
103552
+			       0, 0, 0);
103552
+			goto bail_one;
103552
+		}
103552
+		if ( cert_file_path ) PR_smprintf_free( cert_file_path );
103552
+		continue;
103552
+	bail_one:
103552
+		if ( cert_file_path ) PR_smprintf_free( cert_file_path );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	rv = 1;
103552
+bail:
103552
+	if ( cacerts_dir ) PR_smprintf_free( cacerts_dir );
103552
+	if ( list ) CERT_DestroyCertList( list );
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* returns 1 if successfull;
103552
+   returns -1 if only cert-key pair is NULL or could not be extracted;
103552
+   returns 0 if any other error
103552
+*/
103552
+int
103552
+tlsmc_extract_nssdb( char *dir_name, char **ld_cacertdir, char **ld_cert, char **ld_key )
103552
+{
103552
+	int rv = 0;
103552
+
103552
+	if ( ! dir_name ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_nssdb: FATAL: target dir name empty.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	if ( 0 == tlsmc_extract_cacerts( dir_name ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_nssdb: ERROR: could not export CA certificates.\n",
103552
+		       0, 0, 0 );
3c02b9
+		goto bail;
103552
+	}
103552
+
103552
+	if ( 0 == tlsmc_extract_cert_key_pair( *ld_cert, *ld_key, dir_name ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_extract_nssdb: ERROR: could not export user cert and/or key.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	rv = 1;
103552
+bail:
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+/* BORROWED FROM tls_m.c */
103552
+int
103552
+tlsmc_close_nssdb(NSSInitContext **initctx)
103552
+{
103552
+	if ( *initctx && NSS_ShutdownContext( *initctx ) ) {
103552
+		PRErrorCode errcode = PR_GetError();
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_close_nssdb: ERROR: could not shutdown NSS - error %d:%s.\n",
103552
+		       errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
103552
+		return 0;
103552
+	} else {
103552
+		return 1;
103552
+	}
103552
+}
103552
+
103552
+
103552
+int
103552
+tlsmc_convert( char **ld_cacertdir, char **ld_cert, char **ld_key )
103552
+{
103552
+
103552
+	int rv = 0;
103552
+
103552
+	NSSInitContext *nss_ctx = NULL;
103552
+	char *nssdb_dir_path = NULL;
103552
+	char *nssdb_prefix = NULL;
103552
+	char *pem_dir = NULL;
103552
+	char *readme_path = NULL;
103552
+	char *data = NULL;  // data before checksum
103552
+	char *checksum = NULL;  // checksummed data
103552
+	struct stat stat_buf;
103552
+
103552
+#ifdef LDAP_R_COMPILE
103552
+	ldap_pvt_thread_mutex_lock( &tlsmc_mutex );
103552
+#endif
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_convert: INFO: trying to open NSS DB with CACertDir = `%s'.\n",
103552
+	       *ld_cacertdir, 0, 0 );
103552
+	if ( NULL == ld_cacertdir || NULL == ld_cert || NULL == ld_key ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: ERROR: cannot proceed, some of the arguments are NULL.\n",
103552
+		       0, 0, 0 );
103552
+		rv = 1;
103552
+		goto bail;
103552
+	}
103552
+	if ( 0 == tlsmc_open_nssdb( *ld_cacertdir, &nss_ctx, &nssdb_dir_path, &nssdb_prefix ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: INFO: cannot open the NSS DB, expecting PEM configuration is present.\n",
103552
+		       0, 0, 0 );
103552
+		rv = 1;
103552
+		goto bail;
103552
+	}
103552
+
103552
+	if ( NULL == ( checksum = tlsmc_compute_checksum( nssdb_dir_path, nssdb_prefix,
103552
+	                                                  *ld_cacertdir, *ld_cert, *ld_key,
103552
+	                                                  &data ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: ERROR: could not compute checksum.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	if ( NULL == ( pem_dir = PR_smprintf( "/tmp/openldap-tlsmc-%s-%s-%s",
103552
+	                                      tlsmc_path2name( nssdb_dir_path ),
103552
+	                                      nssdb_prefix,
103552
+	                                      checksum) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: FATAL: could not allocate memory.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( NULL == ( readme_path = PR_smprintf( "%s/" TLSMC_README_FILE_NAME, pem_dir ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: FATAL: could not allocate memory.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_convert: INFO: trying with PEM dir = `%s'.\n",
103552
+	       pem_dir, 0, 0 );
103552
+	if ( 0 == stat( pem_dir, &stat_buf ) ) {
103552
+		if ( S_ISDIR(stat_buf.st_mode) ) {
103552
+			Debug( LDAP_DEBUG_TRACE,
103552
+			       "tlsmc_convert: INFO: using the existing PEM dir.\n",
103552
+			       0, 0, 0 );
103552
+			if ( 0 == stat( readme_path, &stat_buf ) ) {
103552
+				goto pem_dir_exists;
103552
+			} else {
103552
+				Debug( LDAP_DEBUG_ANY,
103552
+				       "tlsmc_convert: ERROR: the PEM dir found does not contain README file. Will remove the PEM dir and try to recreate it.\n",
103552
+				       0, 0, 0 );
103552
+				if ( 0 == tlsmc_remove_dir_recursively( pem_dir ) ) {
103552
+					Debug( LDAP_DEBUG_ANY,
103552
+					       "tlsmc_convert: FATAL: could not remove the PEM dir. Cannot properly set TLS.\n",
103552
+					       0, 0, 0 );
103552
+					goto bail;
103552
+				}
103552
+			}
103552
+		} else {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_convert: FATAL: tried to stat the PEM dir but it is not a directory.\n",
103552
+			       0, 0, 0 );
103552
+			goto bail;
103552
+		}
103552
+	}
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_convert: WARN: will try to create PEM dir.\n",
103552
+	       0, 0, 0 );
103552
+	if ( 0 == tlsmc_prepare_dir( pem_dir ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: FATAL: cannot prepare the PEM dir.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( 0 == tlsmc_extract_nssdb( pem_dir, ld_cacertdir, ld_cert, ld_key ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: FATAL: could not extract from the NSS DB.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( 0 == tlsmc_write_file( readme_path, data, S_IRUSR ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: ERROR: could not create README file.\n",
103552
+		       0, 0, 0 );
103552
+	}
103552
+
103552
+pem_dir_exists:
103552
+	if (*ld_cacertdir) free(*ld_cacertdir);
103552
+	*ld_cacertdir = PR_smprintf( "%s/" TLSMC_CACERTS_DIR_NAME, pem_dir );
103552
+	if ( ! ( ( 0 == stat( *ld_cacertdir, &stat_buf ) )
103552
+	         && S_ISDIR(stat_buf.st_mode) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: WARN: extracted cacerts dir is not present.\n",
103552
+		       0, 0, 0 );
5ed10d
+		if ( *ld_cacertdir ) PR_smprintf_free( *ld_cacertdir );
103552
+		*ld_cacertdir = NULL;
103552
+	}
103552
+
103552
+	if (*ld_cert) free(*ld_cert);
103552
+	*ld_cert = PR_smprintf( "%s/" TLSMC_CERT_FILE_NAME, pem_dir );
103552
+	if ( ! ( ( 0 == stat( *ld_cert, &stat_buf ) )
103552
+	         && ( S_ISREG(stat_buf.st_mode)
103552
+	              || S_ISLNK(stat_buf.st_mode) ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: WARN: extracted cert file is not present.\n",
103552
+		       0, 0, 0 );
5ed10d
+		if ( *ld_cert ) PR_smprintf_free( *ld_cert );
103552
+		*ld_cert = NULL;
103552
+	}
103552
+
103552
+	if (*ld_key) free(*ld_key);
103552
+	*ld_key = PR_smprintf( "%s/" TLSMC_KEY_FILE_NAME, pem_dir );
103552
+	if ( ! ( ( 0 == stat( *ld_key, &stat_buf ) )
103552
+	         && ( S_ISREG(stat_buf.st_mode)
103552
+	              || S_ISLNK(stat_buf.st_mode) ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_convert: WARN: extracted key file is not present.\n",
103552
+		       0, 0, 0 );
5ed10d
+		if ( *ld_key ) PR_smprintf_free( *ld_key );
103552
+		*ld_key = NULL;
103552
+	}
103552
+
103552
+	rv = 1;
103552
+
103552
+bail:
5ed10d
+	if ( checksum ) free( checksum );
103552
+	if ( pem_dir ) PR_smprintf_free( pem_dir );
5ed10d
+	if ( readme_path ) PR_smprintf_free( readme_path );
103552
+	if ( data ) free( data );
103552
+	if ( nssdb_prefix ) free( nssdb_prefix );
103552
+	if ( nssdb_dir_path ) free( nssdb_dir_path );
103552
+	if ( nss_ctx ) tlsmc_close_nssdb( &nss_ctx );
103552
+
103552
+#ifdef LDAP_R_COMPILE
103552
+	ldap_pvt_thread_mutex_unlock( &tlsmc_mutex );
103552
+#endif
103552
+
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+// returns 0 when successful
103552
+int
103552
+tlsmc_intercept_initialization( struct ldapoptions *lo, int is_server )
103552
+{
103552
+	int rv = 0;
103552
+	char *ld_cacertdir = NULL;
103552
+	char *ld_cert = NULL;
103552
+	char *ld_key = NULL;
103552
+
103552
+	ld_cacertdir = lo->ldo_tls_cacertdir ? LDAP_STRDUP( (char *) lo->ldo_tls_cacertdir ) : NULL;
103552
+	ld_cert = lo->ldo_tls_certfile ? LDAP_STRDUP( (char *) lo->ldo_tls_certfile ) : NULL;
103552
+	ld_key = lo->ldo_tls_keyfile ? LDAP_STRDUP( (char *) lo->ldo_tls_keyfile ) : NULL;
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_intercept_initialization: INFO: entry options follow:\n"
103552
+	       "tlsmc_intercept_initialization: INFO: cacertdir = `%s'\n"
103552
+	       "tlsmc_intercept_initialization: INFO: certfile = `%s'\n"
103552
+	       "tlsmc_intercept_initialization: INFO: keyfile = `%s'\n",
103552
+	       lo->ldo_tls_cacertdir, lo->ldo_tls_certfile, lo->ldo_tls_keyfile );
103552
+
103552
+	if ( 0 == tlsmc_convert( &ld_cacertdir, &ld_cert, &ld_key ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_intercept_initialization: FATAL: could not intercept TLS initialization. TLS will not work!\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	if ( lo->ldo_tls_cacertdir ) LDAP_FREE( lo->ldo_tls_cacertdir );
103552
+	lo->ldo_tls_cacertdir = ld_cacertdir ? LDAP_STRDUP( (char *) ld_cacertdir ) : NULL;
103552
+
103552
+	if ( lo->ldo_tls_certfile ) LDAP_FREE( lo->ldo_tls_certfile );
103552
+	lo->ldo_tls_certfile = ld_cert ? LDAP_STRDUP( (char *) ld_cert ) : NULL;
103552
+
103552
+	if ( lo->ldo_tls_keyfile ) LDAP_FREE( lo->ldo_tls_keyfile );
103552
+	lo->ldo_tls_keyfile = ld_key ? LDAP_STRDUP( (char *) ld_key ) : NULL;
103552
+
103552
+	Debug( LDAP_DEBUG_TRACE,
103552
+	       "tlsmc_intercept_initialization: INFO: altered options follow:\n"
103552
+	       "tlsmc_intercept_initialization: INFO: cacertdir = `%s'\n"
103552
+	       "tlsmc_intercept_initialization: INFO: certfile = `%s'\n"
103552
+	       "tlsmc_intercept_initialization: INFO: keyfile = `%s'\n",
103552
+	       lo->ldo_tls_cacertdir, lo->ldo_tls_certfile, lo->ldo_tls_keyfile );
103552
+
103552
+	Debug( LDAP_DEBUG_ANY,
103552
+	       "tlsmc_intercept_initialization: INFO: successfully intercepted TLS initialization. Continuing with OpenSSL only.\n",
103552
+	       0, 0, 0 );
103552
+	rv = 1;
103552
+bail:
103552
+	if ( ld_cacertdir ) LDAP_FREE( ld_cacertdir );
103552
+	if ( ld_cert ) LDAP_FREE( ld_cert );
103552
+	if ( ld_key ) LDAP_FREE( ld_key );
103552
+	return rv;
103552
+}
103552
+
103552
+
103552
+#endif /* HAVE_MOZNSS_COMPATIBILITY */
103552
+/*
103552
+  emacs settings
103552
+  Local Variables:
103552
+  indent-tabs-mode: t
103552
+  tab-width: 4
103552
+  End:
103552
+*/
103552
diff --git a/libraries/libldap/tls_mc.h b/libraries/libldap/tls_mc.h
103552
new file mode 100644
103552
--- /dev/null
103552
+++ b/libraries/libldap/tls_mc.h
103552
@@ -0,0 +1,18 @@
103552
+#ifndef _LDAP_TLSMC_H
103552
+#define _LDAP_TLSMC_H
103552
+
103552
+#include "portable.h"
103552
+
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+
103552
+#include "ldap-int.h"
103552
+
103552
+int
103552
+tlsmc_convert( char **ld_cacertdir, char **ld_cert, char **ld_key );
103552
+
103552
+int
103552
+tlsmc_intercept_initialization( struct ldapoptions *lo, int is_server );
103552
+
103552
+
103552
+#endif /* HAVE_MOZNSS_COMPATIBILITY */
103552
+#endif /* _LDAP_TLSMC_H */
103552
diff --git a/libraries/libldap/tls_mc_ossl.c b/libraries/libldap/tls_mc_ossl.c
103552
new file mode 100644
103552
--- /dev/null
103552
+++ b/libraries/libldap/tls_mc_ossl.c
103552
@@ -0,0 +1,95 @@
103552
+#include "portable.h"
103552
+
103552
+/* This file contains functions that require OpenSSL headers due to some
103552
+   conflicts with what MozNSS defines.
103552
+*/
103552
+
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+
103552
+#include <openssl/x509.h>
103552
+#include <openssl/pem.h>
103552
+#include "ldap-int.h"
103552
+#include <nspr/nspr.h>
103552
+#include <unistd.h>
103552
+#include <errno.h>
103552
+
103552
+
103552
+int
103552
+tlsmc_cert_create_hash_symlink( char *cert_path, char *cacerts_dir )
103552
+{
103552
+	int rv = 0;
103552
+	X509 *cert = NULL;
103552
+	FILE *fp = NULL;
103552
+	unsigned long hash = 0;
103552
+	char *cert_filename_p = NULL;
103552
+	char *last_slash_p = NULL;
103552
+	char *symlink_path = NULL;
103552
+	int cnt = 0;
103552
+
103552
+	if ( NULL == ( fp = fopen( cert_path, "r" ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_cert_create_hash_symlink: ERROR: could not open the cert file.\n",
103552
+		       0, 0, 0 );
103552
+		perror( "tlsmc_cert_create_hash_symlink: ERROR: OS error" );
103552
+		goto bail;
103552
+	}
103552
+	if ( NULL == PEM_read_X509( fp, &cert, NULL, NULL ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_cert_create_hash_symlink: ERROR: could not read PEM data.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+	if ( 0 == ( hash = X509_subject_name_hash( cert ) ) ) {
103552
+		Debug( LDAP_DEBUG_ANY,
103552
+		       "tlsmc_cert_create_hash_symlink: ERROR: could not hash subject.\n",
103552
+		       0, 0, 0 );
103552
+		goto bail;
103552
+	}
103552
+
103552
+	last_slash_p = strrchr( cert_path, '/' );
103552
+	cert_filename_p = last_slash_p ? last_slash_p + 1 : cert_path;
103552
+	for ( cnt = 0; cnt < 10; cnt++ ) {
103552
+		if ( NULL == ( symlink_path = PR_smprintf( "%s/%08lx.%d", cacerts_dir, hash, cnt ) ) ) {
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_cert_create_hash_symlink: ERROR: memory allocation error.\n",
103552
+			       0, 0, 0 );
103552
+			continue;
103552
+		}
103552
+		if ( 0 != symlink( cert_filename_p, symlink_path ) ) {
103552
+			if ( errno == EEXIST ) {
103552
+				Debug( LDAP_DEBUG_ANY,
103552
+				       "tlsmc_cert_create_hash_symlink: INFO: symlink `%s' already exists.\n",
103552
+				       symlink_path, 0, 0 );
103552
+				if ( symlink_path ) PR_smprintf( symlink_path );
103552
+				continue;
103552
+			}
103552
+			Debug( LDAP_DEBUG_ANY,
103552
+			       "tlsmc_cert_create_hash_symlink: ERROR: could not create symlink.\n",
103552
+			       0, 0, 0 );
103552
+			perror( "tlsmc_cert_create_hash_symlink: ERROR: OS error" );
103552
+			goto bail;
103552
+		}
103552
+		Debug( LDAP_DEBUG_TRACE,
103552
+		       "tlsmc_cert_create_hash_symlink: INFO: the cert is now symlinked to %s.\n",
103552
+		       symlink_path, 0, 0 );
103552
+		rv = 1;
103552
+		goto bail;
103552
+	}
103552
+	Debug( LDAP_DEBUG_ANY,
103552
+	       "tlsmc_cert_create_hash_symlink: INFO: could not create symlink (all possible file names taken).\n",
103552
+	       0, 0, 0 );
103552
+bail:
103552
+	if ( symlink_path ) PR_smprintf_free( symlink_path );
103552
+	if ( cert ) X509_free( cert );
103552
+	if ( fp ) fclose( fp );
103552
+	return rv;
103552
+}
103552
+
103552
+#endif /* HAVE_MOZNSS_COMPATIBILITY */
103552
+/*
103552
+  emacs settings
103552
+  Local Variables:
103552
+  indent-tabs-mode: t
103552
+  tab-width: 4
103552
+  End:
103552
+*/
103552
diff --git a/libraries/libldap/tls_mc_ossl.h b/libraries/libldap/tls_mc_ossl.h
103552
new file mode 100644
103552
--- /dev/null
103552
+++ b/libraries/libldap/tls_mc_ossl.h
103552
@@ -0,0 +1,12 @@
103552
+#ifndef _LDAP_TLSMC_OSSL_H
103552
+#define _LDAP_TLSMC_OSSL_H
103552
+
103552
+#include "portable.h"
103552
+
103552
+#ifdef HAVE_MOZNSS_COMPATIBILITY
103552
+
103552
+int
103552
+tlsmc_cert_create_hash_symlink( char *cert_path, char *cacerts_dir );
103552
+
103552
+#endif
103552
+#endif
103552
diff --git a/libraries/libldap_r/Makefile.in b/libraries/libldap_r/Makefile.in
103552
--- a/libraries/libldap_r/Makefile.in
103552
+++ b/libraries/libldap_r/Makefile.in
103552
@@ -28,7 +28,7 @@ XXSRCS    = apitest.c test.c \
103552
 	request.c os-ip.c url.c pagectrl.c sortctrl.c vlvctrl.c \
103552
 	init.c options.c print.c string.c util-int.c schema.c \
103552
 	charray.c os-local.c dnssrv.c utf-8.c utf-8-conv.c \
103552
-	tls2.c tls_o.c tls_g.c tls_m.c \
103552
+	tls2.c tls_o.c tls_g.c tls_m.c tls_mc.c tls_mc_ossl.c \
103552
 	turn.c ppolicy.c dds.c txn.c ldap_sync.c stctrl.c \
103552
 	assertion.c deref.c ldif.c fetch.c
103552
 SRCS	= threads.c rdwr.c rmutex.c tpool.c rq.c \
103552
@@ -46,7 +46,7 @@ OBJS	= threads.lo rdwr.lo rmutex.lo tpool.lo  rq.lo \
103552
 	request.lo os-ip.lo url.lo pagectrl.lo sortctrl.lo vlvctrl.lo \
103552
 	init.lo options.lo print.lo string.lo util-int.lo schema.lo \
103552
 	charray.lo os-local.lo dnssrv.lo utf-8.lo utf-8-conv.lo \
103552
-	tls2.lo tls_o.lo tls_g.lo tls_m.lo \
103552
+	tls2.lo tls_o.lo tls_g.lo tls_m.lo tls_mc.lo tls_mc_ossl.lo \
103552
 	turn.lo ppolicy.lo dds.lo txn.lo ldap_sync.lo stctrl.lo \
103552
 	assertion.lo deref.lo ldif.lo fetch.lo
103552