1 /* tls_m.c - Handle tls/ssl using Mozilla NSS. */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2011 The OpenLDAP Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted only as authorized by the OpenLDAP
12 * A copy of this license is available in the file LICENSE in the
13 * top-level directory of the distribution or, alternatively, at
14 * <http://www.OpenLDAP.org/license.html>.
16 /* ACKNOWLEDGEMENTS: Initial version written by Howard Chu.
17 * Additional support by Rich Megginson.
24 #include "ldap_config.h"
28 #if defined( HAVE_FCNTL_H )
32 #include <ac/stdlib.h>
34 #include <ac/socket.h>
35 #include <ac/string.h>
38 #include <ac/unistd.h>
40 #include <ac/dirent.h>
45 #define READ_PASSWORD_FROM_STDIN
46 #define READ_PASSWORD_FROM_FILE
48 #ifdef READ_PASSWORD_FROM_STDIN
49 #include <termios.h> /* for echo on/off */
52 #include <nspr/nspr.h>
53 #include <nspr/private/pprio.h>
56 #include <nss/sslerr.h>
57 #include <nss/sslproto.h>
58 #include <nss/pk11pub.h>
59 #include <nss/secerr.h>
60 #include <nss/keyhi.h>
61 #include <nss/secmod.h>
64 #undef NSS_VERSION_INT
65 #define NSS_VERSION_INT ((NSS_VMAJOR << 24) | (NSS_VMINOR << 16) | \
66 (NSS_VPATCH << 8) | NSS_VBUILD)
68 /* NSS 3.12.5 and later have NSS_InitContext */
69 #if NSS_VERSION_INT >= 0x030c0500
70 #define HAVE_NSS_INITCONTEXT 1
73 /* NSS 3.12.9 and later have SECMOD_RestartModules */
74 #if NSS_VERSION_INT >= 0x030c0900
75 #define HAVE_SECMOD_RESTARTMODULES 1
78 /* InitContext does not currently work in server mode */
79 /* #define INITCONTEXT_HACK 1 */
81 typedef struct tlsm_ctx {
84 PRBool tc_verify_cert;
85 CERTCertDBHandle *tc_certdb;
88 struct ldaptls *tc_config;
91 PRCallOnceType tc_callonce;
93 char *tc_slotname; /* if using pem */
94 #ifdef HAVE_NSS_INITCONTEXT
95 NSSInitContext *tc_initctx; /* the NSS context */
97 PK11GenericObject **tc_pem_objs; /* array of objects to free */
98 int tc_n_pem_objs; /* number of objects */
100 ldap_pvt_thread_mutex_t tc_refmutex;
104 typedef PRFileDesc tlsm_session;
106 static PRDescIdentity tlsm_layer_id;
108 static const PRIOMethods tlsm_PR_methods;
110 #define PEM_LIBRARY "nsspem"
111 #define PEM_MODULE "PEM"
112 /* hash files for use with cacertdir have this file name suffix */
113 #define PEM_CA_HASH_FILE_SUFFIX ".0"
114 #define PEM_CA_HASH_FILE_SUFFIX_LEN 2
116 static SECMODModule *pem_module;
118 #define DEFAULT_TOKEN_NAME "default"
119 /* sprintf format used to create token name */
120 #define TLSM_PEM_TOKEN_FMT "PEM Token #%ld"
122 static int tlsm_slot_count;
124 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
125 (x)->pValue=(v); (x)->ulValueLen = (l);
127 /* forward declaration */
128 static int tlsm_init( void );
130 #ifdef LDAP_R_COMPILE
133 tlsm_thr_init( void )
137 #endif /* LDAP_R_COMPILE */
140 tlsm_dump_cipher_info(PRFileDesc *fd)
144 for (ii = 0; ii < SSL_NumImplementedCiphers; ++ii) {
145 PRInt32 cipher = (PRInt32)SSL_ImplementedCiphers[ii];
146 PRBool enabled = PR_FALSE;
148 SSLCipherSuiteInfo info;
151 SSL_CipherPrefGet(fd, cipher, &enabled);
153 SSL_CipherPrefGetDefault(cipher, &enabled);
155 SSL_CipherPolicyGet(cipher, &policy);
156 SSL_GetCipherSuiteInfo(cipher, &info, (PRUintn)sizeof(info));
157 Debug( LDAP_DEBUG_TRACE,
158 "TLS: cipher: %d - %s, enabled: %d, ",
159 info.cipherSuite, info.cipherSuiteName, enabled );
160 Debug( LDAP_DEBUG_TRACE,
161 "policy: %d\n", policy, 0, 0 );
167 /* Cipher definitions */
169 char *ossl_name; /* The OpenSSL cipher name */
170 int num; /* The cipher id */
171 int attr; /* cipher attributes: algorithms, etc */
172 int version; /* protocol version valid for this cipher */
173 int bits; /* bits of strength */
174 int alg_bits; /* bits of the algorithm */
175 int strength; /* LOW, MEDIUM, HIGH */
176 int enabled; /* Enabled by default? */
179 /* cipher attributes */
180 #define SSL_kRSA 0x00000001L
181 #define SSL_aRSA 0x00000002L
182 #define SSL_aDSS 0x00000004L
183 #define SSL_DSS SSL_aDSS
184 #define SSL_eNULL 0x00000008L
185 #define SSL_DES 0x00000010L
186 #define SSL_3DES 0x00000020L
187 #define SSL_RC4 0x00000040L
188 #define SSL_RC2 0x00000080L
189 #define SSL_AES 0x00000100L
190 #define SSL_MD5 0x00000200L
191 #define SSL_SHA1 0x00000400L
192 #define SSL_SHA SSL_SHA1
193 #define SSL_RSA (SSL_kRSA|SSL_aRSA)
195 /* cipher strength */
196 #define SSL_NULL 0x00000001L
197 #define SSL_EXPORT40 0x00000002L
198 #define SSL_EXPORT56 0x00000004L
199 #define SSL_LOW 0x00000008L
200 #define SSL_MEDIUM 0x00000010L
201 #define SSL_HIGH 0x00000020L
203 #define SSL2 0x00000001L
204 #define SSL3 0x00000002L
205 /* OpenSSL treats SSL3 and TLSv1 the same */
208 /* Cipher translation */
209 static cipher_properties ciphers_def[] = {
211 {"DES-CBC3-MD5", SSL_EN_DES_192_EDE3_CBC_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_3DES|SSL_MD5, SSL2, 168, 168, SSL_HIGH, SSL_ALLOWED},
212 {"RC2-CBC-MD5", SSL_EN_RC2_128_CBC_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC2|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
213 {"RC4-MD5", SSL_EN_RC4_128_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
214 {"DES-CBC-MD5", SSL_EN_DES_64_CBC_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_MD5, SSL2, 56, 56, SSL_LOW, SSL_ALLOWED},
215 {"EXP-RC2-CBC-MD5", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC2|SSL_MD5, SSL2, 40, 128, SSL_EXPORT40, SSL_ALLOWED},
216 {"EXP-RC4-MD5", SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 40, 128, SSL_EXPORT40, SSL_ALLOWED},
219 {"RC4-MD5", SSL_RSA_WITH_RC4_128_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
220 {"RC4-SHA", SSL_RSA_WITH_RC4_128_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA1, SSL3, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
221 {"DES-CBC3-SHA", SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_3DES|SSL_SHA1, SSL3, 168, 168, SSL_HIGH, SSL_ALLOWED},
222 {"DES-CBC-SHA", SSL_RSA_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA1, SSL3, 56, 56, SSL_LOW, SSL_ALLOWED},
223 {"EXP-RC4-MD5", SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 40, 128, SSL_EXPORT40, SSL_ALLOWED},
224 {"EXP-RC2-CBC-MD5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_kRSA|SSL_aRSA|SSL_RC2|SSL_MD5, SSL3, 0, 0, SSL_EXPORT40, SSL_ALLOWED},
225 {"NULL-MD5", SSL_RSA_WITH_NULL_MD5, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_MD5, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
226 {"NULL-SHA", SSL_RSA_WITH_NULL_SHA, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_SHA1, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
229 {"EXP1024-DES-CBC-SHA", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA, TLS1, 56, 56, SSL_EXPORT56, SSL_ALLOWED},
230 {"EXP1024-RC4-SHA", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA, TLS1, 56, 56, SSL_EXPORT56, SSL_ALLOWED},
231 {"AES128-SHA", TLS_RSA_WITH_AES_128_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_AES|SSL_SHA, TLS1, 128, 128, SSL_HIGH, SSL_ALLOWED},
232 {"AES256-SHA", TLS_RSA_WITH_AES_256_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_AES|SSL_SHA, TLS1, 256, 256, SSL_HIGH, SSL_ALLOWED},
235 #define ciphernum (sizeof(ciphers_def)/sizeof(cipher_properties))
237 /* given err which is the current errno, calls PR_SetError with
238 the corresponding NSPR error code */
240 tlsm_map_error(int err)
246 prError = PR_NO_ACCESS_RIGHTS_ERROR;
249 prError = PR_ADDRESS_IN_USE_ERROR;
252 prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
255 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
258 prError = PR_WOULD_BLOCK_ERROR;
261 * On QNX and Neutrino, EALREADY is defined as EBUSY.
263 #if EALREADY != EBUSY
265 prError = PR_ALREADY_INITIATED_ERROR;
269 prError = PR_BAD_DESCRIPTOR_ERROR;
273 prError = PR_IO_ERROR;
277 prError = PR_FILESYSTEM_MOUNTED_ERROR;
280 prError = PR_CONNECT_ABORTED_ERROR;
283 prError = PR_CONNECT_REFUSED_ERROR;
286 prError = PR_CONNECT_RESET_ERROR;
289 prError = PR_DEADLOCK_ERROR;
293 prError = PR_DIRECTORY_CORRUPTED_ERROR;
298 prError = PR_NO_DEVICE_SPACE_ERROR;
302 prError = PR_FILE_EXISTS_ERROR;
305 prError = PR_ACCESS_FAULT_ERROR;
308 prError = PR_FILE_TOO_BIG_ERROR;
311 prError = PR_HOST_UNREACHABLE_ERROR;
314 prError = PR_IN_PROGRESS_ERROR;
317 prError = PR_PENDING_INTERRUPT_ERROR;
320 prError = PR_INVALID_ARGUMENT_ERROR;
323 prError = PR_IO_ERROR;
326 prError = PR_IS_CONNECTED_ERROR;
329 prError = PR_IS_DIRECTORY_ERROR;
332 prError = PR_LOOP_ERROR;
335 prError = PR_PROC_DESC_TABLE_FULL_ERROR;
338 prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
341 prError = PR_INVALID_ARGUMENT_ERROR;
345 prError = PR_REMOTE_FILE_ERROR;
349 prError = PR_NAME_TOO_LONG_ERROR;
352 prError = PR_NETWORK_UNREACHABLE_ERROR;
355 prError = PR_SYS_DESC_TABLE_FULL_ERROR;
358 * On SCO OpenServer 5, ENOBUFS is defined as ENOSR.
360 #if defined(ENOBUFS) && (ENOBUFS != ENOSR)
362 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
366 prError = PR_FILE_NOT_FOUND_ERROR;
369 prError = PR_FILE_NOT_FOUND_ERROR;
372 prError = PR_FILE_IS_LOCKED_ERROR;
376 prError = PR_REMOTE_FILE_ERROR;
380 prError = PR_OUT_OF_MEMORY_ERROR;
383 prError = PR_INVALID_ARGUMENT_ERROR;
386 prError = PR_NO_DEVICE_SPACE_ERROR;
390 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
394 prError = PR_NOT_CONNECTED_ERROR;
397 prError = PR_NOT_DIRECTORY_ERROR;
400 prError = PR_NOT_SOCKET_ERROR;
403 prError = PR_FILE_NOT_FOUND_ERROR;
406 prError = PR_NOT_TCP_SOCKET_ERROR;
410 prError = PR_BUFFER_OVERFLOW_ERROR;
414 prError = PR_NO_ACCESS_RIGHTS_ERROR;
417 prError = PR_CONNECT_RESET_ERROR;
421 prError = PR_IO_ERROR;
424 case EPROTONOSUPPORT:
425 prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
428 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
431 prError = PR_INVALID_METHOD_ERROR;
434 prError = PR_READ_ONLY_FILESYSTEM_ERROR;
437 prError = PR_INVALID_METHOD_ERROR;
440 prError = PR_IO_TIMEOUT_ERROR;
442 #if EWOULDBLOCK != EAGAIN
444 prError = PR_WOULD_BLOCK_ERROR;
448 prError = PR_NOT_SAME_DEVICE_ERROR;
451 prError = PR_UNKNOWN_ERROR;
454 PR_SetError( prError, err );
458 * cipher_list is an integer array with the following values:
459 * -1: never enable this cipher
464 nss_parse_ciphers(const char *cipherstr, int cipher_list[ciphernum])
473 /* All disabled to start */
474 for (i=0; i<ciphernum; i++)
477 ciphertip = strdup(cipherstr);
478 cipher = ciphers = ciphertip;
480 while (ciphers && (strlen(ciphers))) {
481 while ((*cipher) && (isspace(*cipher)))
486 case '+': /* Add something */
490 case '-': /* Subtract something */
494 case '!': /* Disable something */
503 if ((ciphers = strchr(cipher, ':'))) {
507 /* Do the easy one first */
508 if (!strcmp(cipher, "ALL")) {
509 for (i=0; i<ciphernum; i++) {
510 if (!(ciphers_def[i].attr & SSL_eNULL))
511 cipher_list[i] = action;
513 } else if (!strcmp(cipher, "COMPLEMENTOFALL")) {
514 for (i=0; i<ciphernum; i++) {
515 if ((ciphers_def[i].attr & SSL_eNULL))
516 cipher_list[i] = action;
518 } else if (!strcmp(cipher, "DEFAULT")) {
519 for (i=0; i<ciphernum; i++) {
520 cipher_list[i] = ciphers_def[i].enabled == SSL_ALLOWED ? 1 : 0;
529 while (c && (strlen(c))) {
531 if ((c = strchr(cipher, '+'))) {
535 if (!strcmp(cipher, "RSA")) {
537 } else if ((!strcmp(cipher, "NULL")) || (!strcmp(cipher, "eNULL"))) {
539 } else if (!strcmp(cipher, "AES")) {
541 } else if (!strcmp(cipher, "3DES")) {
543 } else if (!strcmp(cipher, "DES")) {
545 } else if (!strcmp(cipher, "RC4")) {
547 } else if (!strcmp(cipher, "RC2")) {
549 } else if (!strcmp(cipher, "MD5")) {
551 } else if ((!strcmp(cipher, "SHA")) || (!strcmp(cipher, "SHA1"))) {
553 } else if (!strcmp(cipher, "SSLv2")) {
555 } else if (!strcmp(cipher, "SSLv3")) {
557 } else if (!strcmp(cipher, "TLSv1")) {
559 } else if (!strcmp(cipher, "HIGH")) {
560 strength |= SSL_HIGH;
561 } else if (!strcmp(cipher, "MEDIUM")) {
562 strength |= SSL_MEDIUM;
563 } else if (!strcmp(cipher, "LOW")) {
565 } else if ((!strcmp(cipher, "EXPORT")) || (!strcmp(cipher, "EXP"))) {
566 strength |= SSL_EXPORT40|SSL_EXPORT56;
567 } else if (!strcmp(cipher, "EXPORT40")) {
568 strength |= SSL_EXPORT40;
569 } else if (!strcmp(cipher, "EXPORT56")) {
570 strength |= SSL_EXPORT56;
578 /* If we have a mask, apply it. If not then perhaps they provided
579 * a specific cipher to enable.
581 if (mask || strength || protocol) {
582 for (i=0; i<ciphernum; i++) {
583 if (((ciphers_def[i].attr & mask) ||
584 (ciphers_def[i].strength & strength) ||
585 (ciphers_def[i].version & protocol)) &&
586 (cipher_list[i] != -1)) {
587 /* Enable the NULL ciphers only if explicity
589 if (ciphers_def[i].attr & SSL_eNULL) {
590 if (mask & SSL_eNULL)
591 cipher_list[i] = action;
593 cipher_list[i] = action;
597 for (i=0; i<ciphernum; i++) {
598 if (!strcmp(ciphers_def[i].ossl_name, cipher) &&
599 cipher_list[1] != -1)
600 cipher_list[i] = action;
609 /* See if any ciphers were enabled */
611 for (i=0; i<ciphernum; i++) {
612 if (cipher_list[i] == 1)
622 tlsm_parse_ciphers(tlsm_ctx *ctx, const char *str)
624 int cipher_state[ciphernum];
630 rv = nss_parse_ciphers(str, cipher_state);
633 /* First disable everything */
634 for (i = 0; i < SSL_NumImplementedCiphers; i++)
635 SSL_CipherPrefSet(ctx->tc_model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
637 /* Now enable what was requested */
638 for (i=0; i<ciphernum; i++) {
639 SSLCipherSuiteInfo suite;
642 if (SSL_GetCipherSuiteInfo(ciphers_def[i].num, &suite, sizeof suite)
644 enabled = cipher_state[i] < 0 ? 0 : cipher_state[i];
645 if (enabled == SSL_ALLOWED) {
646 if (PK11_IsFIPS() && !suite.isFIPS)
647 enabled = SSL_NOT_ALLOWED;
649 SSL_CipherPrefSet(ctx->tc_model, ciphers_def[i].num, enabled);
654 return rv == 1 ? 0 : -1;
658 tlsm_bad_cert_handler(void *arg, PRFileDesc *ssl)
660 SECStatus success = SECSuccess;
662 tlsm_ctx *ctx = (tlsm_ctx *)arg;
668 err = PORT_GetError();
671 case SEC_ERROR_UNTRUSTED_ISSUER:
672 case SEC_ERROR_UNKNOWN_ISSUER:
673 case SEC_ERROR_EXPIRED_CERTIFICATE:
674 if (ctx->tc_verify_cert) {
675 success = SECFailure;
678 /* we bypass NSS's hostname checks and do our own */
679 case SSL_ERROR_BAD_CERT_DOMAIN:
682 success = SECFailure;
690 tlsm_dump_security_status(PRFileDesc *fd)
692 char * cp; /* bulk cipher name */
693 char * ip; /* cert issuer DN */
694 char * sp; /* cert subject DN */
695 int op; /* High, Low, Off */
696 int kp0; /* total key bits */
697 int kp1; /* secret key bits */
698 SSL3Statistics * ssl3stats = SSL_GetStatistics();
700 SSL_SecurityStatus( fd, &op, &cp, &kp0, &kp1, &ip, &sp );
701 Debug( LDAP_DEBUG_TRACE,
702 "TLS certificate verification: subject: %s, issuer: %s, cipher: %s, ",
703 sp ? sp : "-unknown-", ip ? ip : "-unknown-", cp ? cp : "-unknown-" );
707 Debug( LDAP_DEBUG_TRACE,
708 "security level: %s, secret key bits: %d, total key bits: %d, ",
709 ((op == SSL_SECURITY_STATUS_ON_HIGH) ? "high" :
710 ((op == SSL_SECURITY_STATUS_ON_LOW) ? "low" : "off")),
713 Debug( LDAP_DEBUG_TRACE,
714 "cache hits: %ld, cache misses: %ld, cache not reusable: %ld\n",
715 ssl3stats->hch_sid_cache_hits, ssl3stats->hch_sid_cache_misses,
716 ssl3stats->hch_sid_cache_not_ok );
722 tlsm_handshake_complete_cb( PRFileDesc *fd, void *client_data )
724 tlsm_dump_security_status( fd );
727 #ifdef READ_PASSWORD_FROM_FILE
729 tlsm_get_pin_from_file(const char *token_name, tlsm_ctx *ctx)
732 char *contents = NULL;
735 char *candidate = NULL;
736 PRFileInfo file_info;
737 PRFileDesc *pwd_fileptr = PR_Open( ctx->tc_pin_file, PR_RDONLY, 00400 );
739 /* open the password file */
740 if ( !pwd_fileptr ) {
741 PRErrorCode errcode = PR_GetError();
742 Debug( LDAP_DEBUG_ANY,
743 "TLS: could not open security pin file %s - error %d:%s.\n",
744 ctx->tc_pin_file, errcode,
745 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
749 /* get the file size */
750 if ( PR_SUCCESS != PR_GetFileInfo( ctx->tc_pin_file, &file_info ) ) {
751 PRErrorCode errcode = PR_GetError();
752 Debug( LDAP_DEBUG_ANY,
753 "TLS: could not get file info from pin file %s - error %d:%s.\n",
754 ctx->tc_pin_file, errcode,
755 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
759 /* create a buffer to hold the file contents */
760 if ( !( contents = PR_MALLOC( file_info.size + 1 ) ) ) {
761 PRErrorCode errcode = PR_GetError();
762 Debug( LDAP_DEBUG_ANY,
763 "TLS: could not alloc a buffer for contents of pin file %s - error %d:%s.\n",
764 ctx->tc_pin_file, errcode,
765 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
769 /* read file into the buffer */
770 if( PR_Read( pwd_fileptr, contents, file_info.size ) <= 0 ) {
771 PRErrorCode errcode = PR_GetError();
772 Debug( LDAP_DEBUG_ANY,
773 "TLS: could not read the file contents from pin file %s - error %d:%s.\n",
774 ctx->tc_pin_file, errcode,
775 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
779 /* format is [tokenname:]password EOL [tokenname:]password EOL ... */
780 /* if you want to use a password containing a colon character, use
781 the special tokenname "default" */
782 for ( line = PL_strtok_r( contents, "\r\n", &lasts ); line;
783 line = PL_strtok_r( NULL, "\r\n", &lasts ) ) {
787 continue; /* skip blank lines */
789 colon = PL_strchr( line, ':' );
791 if ( *(colon + 1) && token_name &&
792 !PL_strncmp( token_name, line, colon-line ) ) {
793 candidate = colon + 1; /* found a definite match */
795 } else if ( !PL_strncmp( DEFAULT_TOKEN_NAME, line, colon-line ) ) {
796 candidate = colon + 1; /* found possible match */
798 } else { /* no token name */
804 PR_Close( pwd_fileptr );
807 pwdstr = PL_strdup( candidate );
809 PL_strfree( contents );
813 #endif /* READ_PASSWORD_FROM_FILE */
815 #ifdef READ_PASSWORD_FROM_STDIN
817 * Turn the echoing off on a tty.
822 if ( isatty( fd ) ) {
824 tcgetattr( fd, &tio );
825 tio.c_lflag &= ~ECHO;
826 tcsetattr( fd, TCSAFLUSH, &tio );
831 * Turn the echoing on on a tty.
836 if ( isatty( fd ) ) {
838 tcgetattr( fd, &tio );
840 tcsetattr( fd, TCSAFLUSH, &tio );
841 tcsetattr( fd, TCSAFLUSH, &tio );
844 #endif /* READ_PASSWORD_FROM_STDIN */
847 * This does the actual work of reading the pin/password/pass phrase
850 tlsm_get_pin(PK11SlotInfo *slot, PRBool retry, tlsm_ctx *ctx)
852 char *token_name = NULL;
855 token_name = PK11_GetTokenName( slot );
856 #ifdef READ_PASSWORD_FROM_FILE
857 /* Try to get the passwords from the password file if it exists.
858 * THIS IS UNSAFE and is provided for convenience only. Without this
859 * capability the server would have to be started in foreground mode
860 * if using an encrypted key.
862 if ( ctx->tc_pin_file ) {
863 pwdstr = tlsm_get_pin_from_file( token_name, ctx );
865 #endif /* RETRIEVE_PASSWORD_FROM_FILE */
866 #ifdef READ_PASSWORD_FROM_STDIN
868 int infd = PR_FileDesc2NativeHandle( PR_STDIN );
869 int isTTY = isatty( infd );
870 unsigned char phrase[200];
871 /* Prompt for password */
874 "Please enter pin, password, or pass phrase for security token '%s': ",
875 token_name ? token_name : DEFAULT_TOKEN_NAME );
878 fgets( (char*)phrase, sizeof(phrase), stdin );
880 fprintf( stdout, "\n" );
883 /* stomp on newline */
884 phrase[strlen((char*)phrase)-1] = 0;
886 pwdstr = PL_strdup( (char*)phrase );
889 #endif /* READ_PASSWORD_FROM_STDIN */
894 * PKCS11 devices (including the internal softokn cert/key database)
895 * may be protected by a pin or password or even pass phrase
896 * MozNSS needs a way for the user to provide that
899 tlsm_pin_prompt(PK11SlotInfo *slot, PRBool retry, void *arg)
901 tlsm_ctx *ctx = (tlsm_ctx *)arg;
903 return tlsm_get_pin( slot, retry, ctx );
907 tlsm_get_basic_constraint_extension( CERTCertificate *cert,
908 CERTBasicConstraints *cbcval )
910 SECItem encodedVal = { 0, NULL };
913 rc = CERT_FindCertExtension( cert, SEC_OID_X509_BASIC_CONSTRAINTS,
915 if ( rc != SECSuccess ) {
919 rc = CERT_DecodeBasicConstraintValue( cbcval, &encodedVal );
921 /* free the raw extension data */
922 PORT_Free( encodedVal.data );
928 tlsm_cert_is_self_issued( CERTCertificate *cert )
930 /* A cert is self-issued if its subject and issuer are equal and
931 * both are of non-zero length.
933 PRBool is_self_issued = cert &&
934 (PRBool)SECITEM_ItemsAreEqual( &cert->derIssuer,
935 &cert->derSubject ) &&
936 cert->derSubject.len > 0;
937 return is_self_issued;
941 tlsm_verify_cert(CERTCertDBHandle *handle, CERTCertificate *cert, void *pinarg,
942 PRBool checksig, SECCertificateUsage certUsage, int errorToIgnore )
944 CERTVerifyLog verifylog;
945 SECStatus ret = SECSuccess;
948 /* the log captures information about every cert in the chain, so we can tell
949 which cert caused the problem and what the problem was */
950 memset( &verifylog, 0, sizeof( verifylog ) );
951 verifylog.arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE );
952 if ( verifylog.arena == NULL ) {
953 Debug( LDAP_DEBUG_ANY,
954 "TLS certificate verification: Out of memory for certificate verification logger\n",
958 ret = CERT_VerifyCertificate( handle, cert, checksig, certUsage, PR_Now(), pinarg, &verifylog,
960 if ( ( name = cert->subjectName ) == NULL ) {
961 name = cert->nickname;
963 if ( verifylog.head == NULL ) {
964 /* it is possible for CERT_VerifyCertificate return with an error with no logging */
965 if ( ret != SECSuccess ) {
966 PRErrorCode errcode = PR_GetError();
967 Debug( LDAP_DEBUG_ANY,
968 "TLS: certificate [%s] is not valid - error %d:%s.\n",
969 name ? name : "(unknown)",
970 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
974 CERTVerifyLogNode *node;
976 ret = SECSuccess; /* reset */
977 node = verifylog.head;
979 if ( ( name = node->cert->subjectName ) == NULL ) {
980 name = node->cert->nickname;
983 /* NSS does not like CA certs that have the basic constraints extension
984 with the CA flag set to FALSE - openssl doesn't check if the cert
986 if ( ( node->error == SEC_ERROR_CA_CERT_INVALID ) &&
987 tlsm_cert_is_self_issued( node->cert ) ) {
988 CERTBasicConstraints basicConstraint;
989 SECStatus rv = tlsm_get_basic_constraint_extension( node->cert, &basicConstraint );
990 if ( ( rv == SECSuccess ) && ( basicConstraint.isCA == PR_FALSE ) ) {
991 Debug( LDAP_DEBUG_TRACE,
992 "TLS: certificate [%s] is not correct because it is a CA cert and the "
993 "BasicConstraint CA flag is set to FALSE - allowing for now, but "
994 "please fix your certs if possible\n", name, 0, 0 );
995 } else { /* does not have basicconstraint, or some other error */
997 Debug( LDAP_DEBUG_ANY,
998 "TLS: certificate [%s] is not valid - CA cert is not valid\n",
1001 } else if ( errorToIgnore && ( node->error == errorToIgnore ) ) {
1002 Debug( LDAP_DEBUG_ANY,
1003 "TLS: Warning: ignoring error for certificate [%s] - error %ld:%s.\n",
1004 name, node->error, PR_ErrorToString( node->error, PR_LANGUAGE_I_DEFAULT ) );
1007 Debug( LDAP_DEBUG_ANY,
1008 "TLS: certificate [%s] is not valid - error %ld:%s.\n",
1009 name, node->error, PR_ErrorToString( node->error, PR_LANGUAGE_I_DEFAULT ) );
1012 CERT_DestroyCertificate( node->cert );
1017 PORT_FreeArena( verifylog.arena, PR_FALSE );
1019 if ( ret == SECSuccess ) {
1020 Debug( LDAP_DEBUG_TRACE,
1021 "TLS: certificate [%s] is valid\n", name, 0, 0 );
1028 tlsm_auth_cert_handler(void *arg, PRFileDesc *fd,
1029 PRBool checksig, PRBool isServer)
1031 SECCertificateUsage certUsage = isServer ? certificateUsageSSLClient : certificateUsageSSLServer;
1032 SECStatus ret = SECSuccess;
1033 CERTCertificate *peercert = SSL_PeerCertificate( fd );
1035 ret = tlsm_verify_cert( (CERTCertDBHandle *)arg, peercert,
1036 SSL_RevealPinArg( fd ),
1037 checksig, certUsage, 0 );
1038 CERT_DestroyCertificate( peercert );
1044 tlsm_authenticate_to_slot( tlsm_ctx *ctx, PK11SlotInfo *slot )
1048 if ( SECSuccess != PK11_Authenticate( slot, PR_FALSE, ctx ) ) {
1049 char *token_name = PK11_GetTokenName( slot );
1050 PRErrorCode errcode = PR_GetError();
1051 Debug( LDAP_DEBUG_ANY,
1052 "TLS: could not authenticate to the security token %s - error %d:%s.\n",
1053 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1054 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1056 rc = 0; /* success */
1063 tlsm_nss_shutdown_cb( void *appData, void *nssData )
1065 SECStatus rc = SECSuccess;
1067 SSL_ShutdownServerSessionIDCache();
1068 SSL_ClearSessionCache();
1071 SECMOD_UnloadUserModule( pem_module );
1072 SECMOD_DestroyModule( pem_module );
1079 tlsm_init_pem_module( void )
1082 char *fullname = NULL;
1083 char *configstring = NULL;
1089 /* not loaded - load it */
1090 /* get the system dependent library name */
1091 fullname = PR_GetLibraryName( NULL, PEM_LIBRARY );
1092 /* Load our PKCS#11 module */
1093 configstring = PR_smprintf( "library=%s name=" PEM_MODULE " parameters=\"\"", fullname );
1094 PL_strfree( fullname );
1096 pem_module = SECMOD_LoadUserModule( configstring, NULL, PR_FALSE );
1097 PR_smprintf_free( configstring );
1099 if ( !pem_module || !pem_module->loaded ) {
1101 SECMOD_DestroyModule( pem_module );
1111 tlsm_add_pem_obj( tlsm_ctx *ctx, PK11GenericObject *obj )
1113 int idx = ctx->tc_n_pem_objs;
1114 ctx->tc_n_pem_objs++;
1115 ctx->tc_pem_objs = (PK11GenericObject **)
1116 PORT_Realloc( ctx->tc_pem_objs, ctx->tc_n_pem_objs * sizeof( PK11GenericObject * ) );
1117 ctx->tc_pem_objs[idx] = obj;
1121 tlsm_free_pem_objs( tlsm_ctx *ctx )
1123 /* free in reverse order of allocation */
1124 while ( ctx->tc_n_pem_objs-- ) {
1125 PK11_DestroyGenericObject( ctx->tc_pem_objs[ctx->tc_n_pem_objs] );
1126 ctx->tc_pem_objs[ctx->tc_n_pem_objs] = NULL;
1128 PORT_Free(ctx->tc_pem_objs);
1129 ctx->tc_pem_objs = NULL;
1130 ctx->tc_n_pem_objs = 0;
1134 tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca, PRBool istrusted )
1137 PK11SlotInfo *slot = NULL;
1138 PK11GenericObject *rv;
1139 CK_ATTRIBUTE *attrs;
1140 CK_ATTRIBUTE theTemplate[20];
1141 CK_BBOOL cktrue = CK_TRUE;
1142 CK_BBOOL ckfalse = CK_FALSE;
1143 CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
1144 char tmpslotname[64];
1145 char *slotname = NULL;
1146 const char *ptr = NULL;
1147 char sep = PR_GetDirectorySeparator();
1151 memset( &fi, 0, sizeof(fi) );
1152 status = PR_GetFileInfo( filename, &fi );
1153 if ( PR_SUCCESS != status) {
1154 PRErrorCode errcode = PR_GetError();
1155 Debug( LDAP_DEBUG_ANY,
1156 "TLS: could not read certificate file %s - error %d:%s.\n",
1158 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1162 if ( fi.type != PR_FILE_FILE ) {
1163 PR_SetError(PR_IS_DIRECTORY_ERROR, 0);
1164 Debug( LDAP_DEBUG_ANY,
1165 "TLS: error: the certificate file %s is not a file.\n",
1170 attrs = theTemplate;
1173 slotID = 0; /* CA and trust objects use slot 0 */
1174 PR_snprintf( tmpslotname, sizeof(tmpslotname), TLSM_PEM_TOKEN_FMT, slotID );
1175 slotname = tmpslotname;
1176 istrusted = PR_TRUE;
1178 if ( ctx->tc_slotname == NULL ) { /* need new slot */
1182 slotID = ++tlsm_slot_count;
1184 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
1186 slotname = ctx->tc_slotname;
1188 if ( ( ptr = PL_strrchr( filename, sep ) ) ) {
1189 PL_strfree( ctx->tc_certname );
1192 /* pemnss conflates trusted certs with CA certs - since there can
1193 be more than one CA cert in a file (e.g. ca-bundle.crt) pemnss
1194 numbers each trusted cert - in the case of a server cert, there will be
1195 only one, so it will be number 0 */
1196 ctx->tc_certname = PR_smprintf( "%s:%s - 0", slotname, ptr );
1198 ctx->tc_certname = PR_smprintf( "%s:%s", slotname, ptr );
1203 slot = PK11_FindSlotByName( slotname );
1206 PRErrorCode errcode = PR_GetError();
1207 Debug( LDAP_DEBUG_ANY,
1208 "TLS: could not find the slot for certificate %s - error %d:%s.\n",
1209 ctx->tc_certname, errcode,
1210 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1214 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1215 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1216 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1218 PK11_SETATTRS( attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1220 PK11_SETATTRS( attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) ); attrs++;
1222 /* This loads the certificate in our PEM module into the appropriate
1225 rv = PK11_CreateGenericObject( slot, theTemplate, 4, PR_FALSE /* isPerm */ );
1227 PK11_FreeSlot( slot );
1230 PRErrorCode errcode = PR_GetError();
1231 Debug( LDAP_DEBUG_ANY,
1232 "TLS: could not add the certificate %s - error %d:%s.\n",
1233 ctx->tc_certname, errcode,
1234 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1238 tlsm_add_pem_obj( ctx, rv );
1244 tlsm_add_key_from_file( tlsm_ctx *ctx, const char *filename )
1247 PK11SlotInfo * slot = NULL;
1248 PK11GenericObject *rv;
1249 CK_ATTRIBUTE *attrs;
1250 CK_ATTRIBUTE theTemplate[20];
1251 CK_BBOOL cktrue = CK_TRUE;
1252 CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
1257 memset( &fi, 0, sizeof(fi) );
1258 status = PR_GetFileInfo( filename, &fi );
1259 if ( PR_SUCCESS != status) {
1260 PRErrorCode errcode = PR_GetError();
1261 Debug( LDAP_DEBUG_ANY,
1262 "TLS: could not read key file %s - error %d:%s.\n",
1264 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1268 if ( fi.type != PR_FILE_FILE ) {
1269 PR_SetError(PR_IS_DIRECTORY_ERROR, 0);
1270 Debug( LDAP_DEBUG_ANY,
1271 "TLS: error: the key file %s is not a file.\n",
1276 attrs = theTemplate;
1278 if ( ctx->tc_slotname == NULL ) { /* need new slot */
1279 slotID = ++tlsm_slot_count;
1280 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
1282 slot = PK11_FindSlotByName( ctx->tc_slotname );
1285 PRErrorCode errcode = PR_GetError();
1286 Debug( LDAP_DEBUG_ANY,
1287 "TLS: could not find the slot %s for the private key - error %d:%s.\n",
1288 ctx->tc_slotname, errcode,
1289 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1293 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1294 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1295 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1296 rv = PK11_CreateGenericObject( slot, theTemplate, 3, PR_FALSE /* isPerm */ );
1299 PRErrorCode errcode = PR_GetError();
1300 Debug( LDAP_DEBUG_ANY,
1301 "TLS: could not add the certificate %s - error %d:%s.\n",
1302 ctx->tc_certname, errcode,
1303 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1306 /* When adding an encrypted key the PKCS#11 will be set as removed */
1307 /* This will force the token to be seen as re-inserted */
1308 SECMOD_WaitForAnyTokenEvent( pem_module, 0, 0 );
1309 PK11_IsPresent( slot );
1313 PK11_FreeSlot( slot );
1316 tlsm_add_pem_obj( ctx, rv );
1322 tlsm_init_ca_certs( tlsm_ctx *ctx, const char *cacertfile, const char *cacertdir )
1324 PRBool isca = PR_TRUE;
1325 PRStatus status = PR_SUCCESS;
1326 PRErrorCode errcode = PR_SUCCESS;
1328 if ( !cacertfile && !cacertdir ) {
1329 /* no checking - not good, but allowed */
1334 int rc = tlsm_add_cert_from_file( ctx, cacertfile, isca, PR_TRUE );
1336 errcode = PR_GetError();
1337 Debug( LDAP_DEBUG_ANY,
1338 "TLS: %s is not a valid CA certificate file - error %d:%s.\n",
1339 cacertfile, errcode,
1340 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1341 /* failure with cacertfile is a hard failure even if cacertdir is
1342 also specified and contains valid CA cert files */
1343 status = PR_FAILURE;
1345 Debug( LDAP_DEBUG_TRACE,
1346 "TLS: loaded CA certificate file %s.\n",
1351 /* if cacertfile above failed, we will return failure, even
1352 if there is a valid CA cert in cacertdir - but we still
1353 process cacertdir in case the user has enabled trace level
1354 debugging so they can see the processing for cacertdir too */
1355 /* any cacertdir failures are "soft" failures - if the user specifies
1356 no cert checking, then we allow the tls/ssl to continue, no matter
1357 what was specified for cacertdir, or the contents of the directory
1358 - this is different behavior than that of cacertfile */
1363 PRStatus fistatus = PR_FAILURE;
1365 memset( &fi, 0, sizeof(fi) );
1366 fistatus = PR_GetFileInfo( cacertdir, &fi );
1367 if ( PR_SUCCESS != fistatus) {
1368 errcode = PR_GetError();
1369 Debug( LDAP_DEBUG_ANY,
1370 "TLS: could not get info about the CA certificate directory %s - error %d:%s.\n",
1372 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1376 if ( fi.type != PR_FILE_DIRECTORY ) {
1377 Debug( LDAP_DEBUG_ANY,
1378 "TLS: error: the CA certificate directory %s is not a directory.\n",
1383 dir = PR_OpenDir( cacertdir );
1384 if ( NULL == dir ) {
1385 errcode = PR_GetError();
1386 Debug( LDAP_DEBUG_ANY,
1387 "TLS: could not open the CA certificate directory %s - error %d:%s.\n",
1389 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1394 entry = PR_ReadDir( dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN );
1395 if ( ( NULL != entry ) && ( NULL != entry->name ) ) {
1396 char *fullpath = NULL;
1399 ptr = PL_strrstr( entry->name, PEM_CA_HASH_FILE_SUFFIX );
1400 if ( ( ptr == NULL ) || ( *(ptr + PEM_CA_HASH_FILE_SUFFIX_LEN) != '\0' ) ) {
1401 Debug( LDAP_DEBUG_TRACE,
1402 "TLS: file %s does not end in [%s] - does not appear to be a CA certificate "
1403 "directory file with a properly hashed file name - skipping.\n",
1404 entry->name, PEM_CA_HASH_FILE_SUFFIX, 0 );
1407 fullpath = PR_smprintf( "%s/%s", cacertdir, entry->name );
1408 if ( !tlsm_add_cert_from_file( ctx, fullpath, isca, PR_TRUE ) ) {
1409 Debug( LDAP_DEBUG_TRACE,
1410 "TLS: loaded CA certificate file %s from CA certificate directory %s.\n",
1411 fullpath, cacertdir, 0 );
1413 errcode = PR_GetError();
1414 Debug( LDAP_DEBUG_TRACE,
1415 "TLS: %s is not a valid CA certificate file - error %d:%s.\n",
1417 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1419 PR_smprintf_free( fullpath );
1421 } while ( NULL != entry );
1425 if ( status != PR_SUCCESS ) {
1433 * NSS supports having multiple cert/key databases in the same
1434 * directory, each one having a unique string prefix e.g.
1435 * slapd-01-cert8.db - the prefix here is "slapd-01-"
1436 * this function examines the given certdir - if it looks like
1437 * /path/to/directory/prefix it will return the
1438 * /path/to/directory part in realcertdir, and the prefix in prefix
1441 tlsm_get_certdb_prefix( const char *certdir, char **realcertdir, char **prefix )
1443 char sep = PR_GetDirectorySeparator();
1445 struct PRFileInfo prfi;
1448 *realcertdir = (char *)certdir; /* default is the one passed in */
1450 /* if certdir is not given, just return */
1455 prc = PR_GetFileInfo( certdir, &prfi );
1456 /* if certdir exists (file or directory) then it cannot specify a prefix */
1457 if ( prc == PR_SUCCESS ) {
1461 /* if certdir was given, and there is a '/' in certdir, see if there
1462 is anything after the last '/' - if so, assume it is the prefix */
1463 if ( ( ( ptr = strrchr( certdir, sep ) ) ) && *(ptr+1) ) {
1464 *realcertdir = PL_strndup( certdir, ptr-certdir );
1465 *prefix = PL_strdup( ptr+1 );
1472 * This is the part of the init we defer until we get the
1473 * actual security configuration information. This is
1474 * only called once, protected by a PRCallOnce
1475 * NOTE: This must be done before the first call to SSL_ImportFD,
1476 * especially the setting of the policy
1477 * NOTE: This must be called after fork()
1480 tlsm_deferred_init( void *arg )
1482 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1483 struct ldaptls *lt = ctx->tc_config;
1484 const char *securitydirs[3];
1487 PRErrorCode errcode = 1;
1488 #ifdef HAVE_NSS_INITCONTEXT
1489 NSSInitParameters initParams;
1490 NSSInitContext *initctx = NULL;
1495 #ifdef HAVE_SECMOD_RESTARTMODULES
1496 /* NSS enforces the pkcs11 requirement that modules should be unloaded after
1497 a fork() - since there is no portable way to determine if NSS has been
1498 already initialized in a parent process, we just call SECMOD_RestartModules
1499 with force == FALSE - if the module has been unloaded due to a fork, it will
1500 be reloaded, otherwise, it is a no-op */
1501 if ( SECFailure == ( rc = SECMOD_RestartModules(PR_FALSE /* do not force */) ) ) {
1502 errcode = PORT_GetError();
1503 if ( errcode != SEC_ERROR_NOT_INITIALIZED ) {
1504 Debug( LDAP_DEBUG_TRACE,
1505 "TLS: could not restart the security modules: %d:%s\n",
1506 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1513 #ifdef HAVE_NSS_INITCONTEXT
1514 memset( &initParams, 0, sizeof( initParams ) );
1515 initParams.length = sizeof( initParams );
1516 #endif /* HAVE_NSS_INITCONTEXT */
1518 #ifndef HAVE_NSS_INITCONTEXT
1519 if ( !NSS_IsInitialized() ) {
1520 #endif /* HAVE_NSS_INITCONTEXT */
1522 MOZNSS_DIR will override everything else - you can
1523 always set MOZNSS_DIR to force the use of this
1525 If using MOZNSS, specify the location of the moznss db dir
1526 in the cacertdir directive of the OpenLDAP configuration.
1527 DEFAULT_MOZNSS_DIR will only be used if the code cannot
1528 find a security dir to use based on the current
1532 securitydirs[nn++] = PR_GetEnv( "MOZNSS_DIR" );
1533 securitydirs[nn++] = lt->lt_cacertdir;
1534 securitydirs[nn++] = PR_GetEnv( "DEFAULT_MOZNSS_DIR" );
1535 for ( ii = 0; !done && ( ii < nn ); ++ii ) {
1536 char *realcertdir = NULL;
1537 const char *defprefix = "";
1538 char *prefix = (char *)defprefix;
1539 const char *securitydir = securitydirs[ii];
1540 if ( NULL == securitydir ) {
1544 tlsm_get_certdb_prefix( securitydir, &realcertdir, &prefix );
1545 #ifdef HAVE_NSS_INITCONTEXT
1546 #ifdef INITCONTEXT_HACK
1547 if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
1548 rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
1550 initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
1551 &initParams, NSS_INIT_READONLY );
1552 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1555 initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
1556 &initParams, NSS_INIT_READONLY );
1557 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1560 rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
1563 if ( rc != SECSuccess ) {
1564 errcode = PORT_GetError();
1565 if ( securitydirs[ii] != lt->lt_cacertdir) {
1566 Debug( LDAP_DEBUG_TRACE,
1567 "TLS: could not initialize moznss using security dir %s prefix %s - error %d.\n",
1568 realcertdir, prefix, errcode );
1572 Debug( LDAP_DEBUG_TRACE, "TLS: using moznss security dir %s prefix %s.\n",
1573 realcertdir, prefix, 0 );
1577 if ( realcertdir != securitydir ) {
1578 PL_strfree( realcertdir );
1580 if ( prefix != defprefix ) {
1581 PL_strfree( prefix );
1585 if ( errcode ) { /* no moznss db found, or not using moznss db */
1586 #ifdef HAVE_NSS_INITCONTEXT
1587 int flags = NSS_INIT_READONLY|NSS_INIT_NOCERTDB|NSS_INIT_NOMODDB;
1588 #ifdef INITCONTEXT_HACK
1589 if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
1590 rc = NSS_NoDB_Init( NULL );
1592 initctx = NSS_InitContext( "", "", "", SECMOD_DB,
1593 &initParams, flags );
1594 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1597 initctx = NSS_InitContext( "", "", "", SECMOD_DB,
1598 &initParams, flags );
1599 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1602 rc = NSS_NoDB_Init( NULL );
1604 if ( rc != SECSuccess ) {
1605 errcode = PORT_GetError();
1606 Debug( LDAP_DEBUG_ANY,
1607 "TLS: could not initialize moznss - error %d:%s.\n",
1608 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1612 #ifdef HAVE_NSS_INITCONTEXT
1613 ctx->tc_initctx = initctx;
1616 /* initialize the PEM module */
1617 if ( tlsm_init_pem_module() ) {
1618 errcode = PORT_GetError();
1619 Debug( LDAP_DEBUG_ANY,
1620 "TLS: could not initialize moznss PEM module - error %d:%s.\n",
1621 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1625 if ( tlsm_init_ca_certs( ctx, lt->lt_cacertfile, lt->lt_cacertdir ) ) {
1626 /* if we tried to use lt->lt_cacertdir as an NSS key/cert db, errcode
1627 will be a value other than 1 - print an error message so that the
1628 user will know that failed too */
1629 if ( ( errcode != 1 ) && ( lt->lt_cacertdir ) ) {
1630 char *realcertdir = NULL;
1631 char *prefix = NULL;
1632 tlsm_get_certdb_prefix( lt->lt_cacertdir, &realcertdir, &prefix );
1633 Debug( LDAP_DEBUG_TRACE,
1634 "TLS: could not initialize moznss using security dir %s prefix %s - error %d.\n",
1635 realcertdir, prefix ? prefix : "", errcode );
1636 if ( realcertdir != lt->lt_cacertdir ) {
1637 PL_strfree( realcertdir );
1639 PL_strfree( prefix );
1644 ctx->tc_using_pem = PR_TRUE;
1647 #ifdef HAVE_NSS_INITCONTEXT
1648 if ( !ctx->tc_initctx ) {
1649 ctx->tc_initctx = initctx;
1653 NSS_SetDomesticPolicy();
1655 PK11_SetPasswordFunc( tlsm_pin_prompt );
1657 /* register cleanup function */
1658 /* delete the old one, if any */
1659 NSS_UnregisterShutdown( tlsm_nss_shutdown_cb, NULL );
1660 NSS_RegisterShutdown( tlsm_nss_shutdown_cb, NULL );
1662 #ifndef HAVE_NSS_INITCONTEXT
1664 #endif /* HAVE_NSS_INITCONTEXT */
1670 tlsm_authenticate( tlsm_ctx *ctx, const char *certname, const char *pininfo )
1672 const char *colon = NULL;
1673 char *token_name = NULL;
1674 PK11SlotInfo *slot = NULL;
1677 if ( !certname || !*certname ) {
1681 if ( ( colon = PL_strchr( certname, ':' ) ) ) {
1682 token_name = PL_strndup( certname, colon-certname );
1686 slot = PK11_FindSlotByName( token_name );
1688 slot = PK11_GetInternalKeySlot();
1692 PRErrorCode errcode = PR_GetError();
1693 Debug( LDAP_DEBUG_ANY,
1694 "TLS: could not find the slot for security token %s - error %d:%s.\n",
1695 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1696 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1700 rc = tlsm_authenticate_to_slot( ctx, slot );
1703 PL_strfree( token_name );
1705 PK11_FreeSlot( slot );
1712 * Find and verify the certificate.
1713 * Either fd is given, in which case the cert will be taken from it via SSL_PeerCertificate
1714 * or certname is given, and it will be searched for by name
1717 tlsm_find_and_verify_cert_key(tlsm_ctx *ctx, PRFileDesc *fd, const char *certname, int isServer, CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey)
1719 CERTCertificate *cert = NULL;
1721 void *pin_arg = NULL;
1722 SECKEYPrivateKey *key = NULL;
1724 pin_arg = SSL_RevealPinArg( fd );
1726 cert = PK11_FindCertFromNickname( certname, pin_arg );
1728 PRErrorCode errcode = PR_GetError();
1729 Debug( LDAP_DEBUG_ANY,
1730 "TLS: error: the certificate %s could not be found in the database - error %d:%s\n",
1731 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1735 /* we are verifying the peer cert
1736 we also need to swap the isServer meaning */
1737 cert = SSL_PeerCertificate( fd );
1739 PRErrorCode errcode = PR_GetError();
1740 Debug( LDAP_DEBUG_ANY,
1741 "TLS: error: could not get the certificate from the peer connection - error %d:%s\n",
1742 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), NULL );
1745 isServer = !isServer; /* verify the peer's cert instead */
1748 if ( ctx->tc_slotname ) {
1749 PK11SlotInfo *slot = PK11_FindSlotByName( ctx->tc_slotname );
1750 key = PK11_FindPrivateKeyFromCert( slot, cert, NULL );
1751 PK11_FreeSlot( slot );
1753 key = PK11_FindKeyByAnyCert( cert, pin_arg );
1757 SECCertificateUsage certUsage;
1758 PRBool checkSig = PR_TRUE;
1762 *pRetKey = key; /* caller will deal with this */
1764 SECKEY_DestroyPrivateKey( key );
1767 certUsage = certificateUsageSSLServer;
1769 certUsage = certificateUsageSSLClient;
1771 if ( ctx->tc_verify_cert ) {
1774 checkSig = PR_FALSE;
1776 /* may not have a CA cert - ok - ignore SEC_ERROR_UNKNOWN_ISSUER */
1777 status = tlsm_verify_cert( ctx->tc_certdb, cert, pin_arg,
1778 checkSig, certUsage, SEC_ERROR_UNKNOWN_ISSUER );
1779 if ( status == SECSuccess ) {
1783 PRErrorCode errcode = PR_GetError();
1784 Debug( LDAP_DEBUG_ANY,
1785 "TLS: error: could not find the private key for certificate %s - error %d:%s\n",
1786 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1790 *pRetCert = cert; /* caller will deal with this */
1792 CERT_DestroyCertificate( cert );
1799 tlsm_get_client_auth_data( void *arg, PRFileDesc *fd,
1800 CERTDistNames *caNames, CERTCertificate **pRetCert,
1801 SECKEYPrivateKey **pRetKey )
1803 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1806 /* don't need caNames - this function will call CERT_VerifyCertificateNow
1807 which will verify the cert against the known CAs */
1808 rc = tlsm_find_and_verify_cert_key( ctx, fd, ctx->tc_certname, 0, pRetCert, pRetKey );
1810 Debug( LDAP_DEBUG_ANY,
1811 "TLS: error: unable to perform client certificate authentication for "
1812 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1820 * ctx must have a tc_model that is valid
1821 * certname is in the form [<tokenname>:]<certnickname>
1822 * where <tokenname> is the name of the PKCS11 token
1823 * and <certnickname> is the nickname of the cert/key in
1827 tlsm_clientauth_init( tlsm_ctx *ctx )
1829 SECStatus status = SECFailure;
1832 rc = tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, 0, NULL, NULL );
1834 Debug( LDAP_DEBUG_ANY,
1835 "TLS: error: unable to set up client certificate authentication for "
1836 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1840 status = SSL_GetClientAuthDataHook( ctx->tc_model,
1841 tlsm_get_client_auth_data,
1844 return ( status == SECSuccess ? 0 : -1 );
1848 * Tear down the TLS subsystem. Should only be called once.
1851 tlsm_destroy( void )
1856 tlsm_ctx_new ( struct ldapoptions *lo )
1860 ctx = LDAP_MALLOC( sizeof (*ctx) );
1863 #ifdef LDAP_R_COMPILE
1864 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
1866 ctx->tc_config = &lo->ldo_tls_info; /* pointer into lo structure - must have global scope and must not go away before we can do real init */
1867 ctx->tc_certdb = NULL;
1868 ctx->tc_certname = NULL;
1869 ctx->tc_pin_file = NULL;
1870 ctx->tc_model = NULL;
1871 memset(&ctx->tc_callonce, 0, sizeof(ctx->tc_callonce));
1872 ctx->tc_require_cert = lo->ldo_tls_require_cert;
1873 ctx->tc_verify_cert = PR_FALSE;
1874 ctx->tc_using_pem = PR_FALSE;
1875 ctx->tc_slotname = NULL;
1876 #ifdef HAVE_NSS_INITCONTEXT
1877 ctx->tc_initctx = NULL;
1878 #endif /* HAVE_NSS_INITCONTEXT */
1879 ctx->tc_pem_objs = NULL;
1880 ctx->tc_n_pem_objs = 0;
1882 return (tls_ctx *)ctx;
1886 tlsm_ctx_ref( tls_ctx *ctx )
1888 tlsm_ctx *c = (tlsm_ctx *)ctx;
1889 LDAP_MUTEX_LOCK( &c->tc_refmutex );
1891 LDAP_MUTEX_UNLOCK( &c->tc_refmutex );
1895 tlsm_ctx_free ( tls_ctx *ctx )
1897 tlsm_ctx *c = (tlsm_ctx *)ctx;
1902 LDAP_MUTEX_LOCK( &c->tc_refmutex );
1903 refcount = --c->tc_refcnt;
1904 LDAP_MUTEX_UNLOCK( &c->tc_refmutex );
1908 PR_Close( c->tc_model );
1909 c->tc_certdb = NULL; /* if not the default, may have to clean up */
1910 PL_strfree( c->tc_certname );
1911 c->tc_certname = NULL;
1912 PL_strfree( c->tc_pin_file );
1913 c->tc_pin_file = NULL;
1914 PL_strfree( c->tc_slotname );
1915 tlsm_free_pem_objs( c );
1916 #ifdef HAVE_NSS_INITCONTEXT
1918 NSS_ShutdownContext( c->tc_initctx );
1919 c->tc_initctx = NULL;
1920 #endif /* HAVE_NSS_INITCONTEXT */
1921 #ifdef LDAP_R_COMPILE
1922 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
1928 * initialize a new TLS context
1931 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
1933 tlsm_ctx *ctx = (tlsm_ctx *)lo->ldo_tls_ctx;
1934 ctx->tc_is_server = is_server;
1940 tlsm_deferred_ctx_init( void *arg )
1942 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1943 PRBool sslv2 = PR_FALSE;
1944 PRBool sslv3 = PR_TRUE;
1945 PRBool tlsv1 = PR_TRUE;
1946 PRBool request_cert = PR_FALSE;
1947 PRInt32 require_cert = PR_FALSE;
1951 if ( tlsm_deferred_init( ctx ) ) {
1952 Debug( LDAP_DEBUG_ANY,
1953 "TLS: could perform TLS system initialization.\n",
1958 ctx->tc_certdb = CERT_GetDefaultCertDB(); /* If there is ever a per-context db, change this */
1960 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
1962 ctx->tc_model = SSL_ImportFD( NULL, fd );
1965 if ( !ctx->tc_model ) {
1966 PRErrorCode err = PR_GetError();
1967 Debug( LDAP_DEBUG_ANY,
1968 "TLS: could perform TLS socket I/O layer initialization - error %d:%s.\n",
1969 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1977 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE ) ) {
1978 Debug( LDAP_DEBUG_ANY,
1979 "TLS: could not set secure mode on.\n",
1984 lt = ctx->tc_config;
1986 /* default is sslv3 and tlsv1 */
1987 if ( lt->lt_protocol_min ) {
1988 if ( lt->lt_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 ) {
1990 } else if ( lt->lt_protocol_min <= LDAP_OPT_X_TLS_PROTOCOL_SSL2 ) {
1992 Debug( LDAP_DEBUG_ANY,
1993 "TLS: warning: minimum TLS protocol level set to "
1994 "include SSLv2 - SSLv2 is insecure - do not use\n", 0, 0, 0 );
1997 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL2, sslv2 ) ) {
1998 Debug( LDAP_DEBUG_ANY,
1999 "TLS: could not set SSLv2 mode on.\n",
2003 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL3, sslv3 ) ) {
2004 Debug( LDAP_DEBUG_ANY,
2005 "TLS: could not set SSLv3 mode on.\n",
2009 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_TLS, tlsv1 ) ) {
2010 Debug( LDAP_DEBUG_ANY,
2011 "TLS: could not set TLSv1 mode on.\n",
2016 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !ctx->tc_is_server ) ) {
2017 Debug( LDAP_DEBUG_ANY,
2018 "TLS: could not set handshake as client.\n",
2022 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, ctx->tc_is_server ) ) {
2023 Debug( LDAP_DEBUG_ANY,
2024 "TLS: could not set handshake as server.\n",
2029 if ( lt->lt_ciphersuite &&
2030 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
2031 Debug( LDAP_DEBUG_ANY,
2032 "TLS: could not set cipher list %s.\n",
2033 lt->lt_ciphersuite, 0, 0 );
2035 } else if ( tlsm_parse_ciphers( ctx, "DEFAULT" ) ) {
2036 Debug( LDAP_DEBUG_ANY,
2037 "TLS: could not set cipher list DEFAULT.\n",
2042 if ( ctx->tc_require_cert ) {
2043 request_cert = PR_TRUE;
2044 require_cert = SSL_REQUIRE_NO_ERROR;
2045 if ( ctx->tc_require_cert == LDAP_OPT_X_TLS_DEMAND ||
2046 ctx->tc_require_cert == LDAP_OPT_X_TLS_HARD ) {
2047 require_cert = SSL_REQUIRE_ALWAYS;
2049 if ( ctx->tc_require_cert != LDAP_OPT_X_TLS_ALLOW )
2050 ctx->tc_verify_cert = PR_TRUE;
2052 ctx->tc_verify_cert = PR_FALSE;
2055 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUEST_CERTIFICATE, request_cert ) ) {
2056 Debug( LDAP_DEBUG_ANY,
2057 "TLS: could not set request certificate mode.\n",
2062 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUIRE_CERTIFICATE, require_cert ) ) {
2063 Debug( LDAP_DEBUG_ANY,
2064 "TLS: could not set require certificate mode.\n",
2069 /* set up our cert and key, if any */
2070 if ( lt->lt_certfile ) {
2071 /* if using the PEM module, load the PEM file specified by lt_certfile */
2072 /* otherwise, assume this is the name of a cert already in the db */
2073 if ( ctx->tc_using_pem ) {
2074 /* this sets ctx->tc_certname to the correct value */
2075 int rc = tlsm_add_cert_from_file( ctx, lt->lt_certfile, PR_FALSE, PR_TRUE );
2080 PL_strfree( ctx->tc_certname );
2081 ctx->tc_certname = PL_strdup( lt->lt_certfile );
2085 if ( lt->lt_keyfile ) {
2086 /* if using the PEM module, load the PEM file specified by lt_keyfile */
2087 /* otherwise, assume this is the pininfo for the key */
2088 if ( ctx->tc_using_pem ) {
2089 /* this sets ctx->tc_certname to the correct value */
2090 int rc = tlsm_add_key_from_file( ctx, lt->lt_keyfile );
2095 PL_strfree( ctx->tc_pin_file );
2096 ctx->tc_pin_file = PL_strdup( lt->lt_keyfile );
2100 /* Set up callbacks for use by clients */
2101 if ( !ctx->tc_is_server ) {
2102 if ( SSL_OptionSet( ctx->tc_model, SSL_NO_CACHE, PR_TRUE ) != SECSuccess ) {
2103 PRErrorCode err = PR_GetError();
2104 Debug( LDAP_DEBUG_ANY,
2105 "TLS: error: could not set nocache option for moznss - error %d:%s\n",
2106 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2110 if ( SSL_BadCertHook( ctx->tc_model, tlsm_bad_cert_handler, ctx ) != SECSuccess ) {
2111 PRErrorCode err = PR_GetError();
2112 Debug( LDAP_DEBUG_ANY,
2113 "TLS: error: could not set bad cert handler for moznss - error %d:%s\n",
2114 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2119 since a cert has been specified, assume the client wants to do cert auth
2121 if ( ctx->tc_certname ) {
2122 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
2123 Debug( LDAP_DEBUG_ANY,
2124 "TLS: error: unable to authenticate to the security device for certificate %s\n",
2125 ctx->tc_certname, 0, 0 );
2128 if ( tlsm_clientauth_init( ctx ) ) {
2129 Debug( LDAP_DEBUG_ANY,
2130 "TLS: error: unable to set up client certificate authentication using %s\n",
2131 ctx->tc_certname, 0, 0 );
2135 } else { /* set up secure server */
2137 CERTCertificate *serverCert;
2138 SECKEYPrivateKey *serverKey;
2141 /* must have a certificate for the server to use */
2142 if ( !ctx->tc_certname ) {
2143 Debug( LDAP_DEBUG_ANY,
2144 "TLS: error: no server certificate: must specify a certificate for the server to use\n",
2149 /* authenticate to the server's token - this will do nothing
2150 if the key/cert db is not password protected */
2151 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
2152 Debug( LDAP_DEBUG_ANY,
2153 "TLS: error: unable to authenticate to the security device for certificate %s\n",
2154 ctx->tc_certname, 0, 0 );
2158 /* get the server's key and cert */
2159 if ( tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, ctx->tc_is_server,
2160 &serverCert, &serverKey ) ) {
2161 Debug( LDAP_DEBUG_ANY,
2162 "TLS: error: unable to find and verify server's cert and key for certificate %s\n",
2163 ctx->tc_certname, 0, 0 );
2167 certKEA = NSS_FindCertKEAType( serverCert );
2168 /* configure the socket to be a secure server socket */
2169 status = SSL_ConfigSecureServer( ctx->tc_model, serverCert, serverKey, certKEA );
2170 /* SSL_ConfigSecureServer copies these */
2171 CERT_DestroyCertificate( serverCert );
2172 SECKEY_DestroyPrivateKey( serverKey );
2174 if ( SECSuccess != status ) {
2175 PRErrorCode err = PR_GetError();
2176 Debug( LDAP_DEBUG_ANY,
2177 "TLS: error: unable to configure secure server using certificate %s - error %d:%s\n",
2178 ctx->tc_certname, err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) );
2183 /* Callback for authenticating certificate */
2184 if ( SSL_AuthCertificateHook( ctx->tc_model, tlsm_auth_cert_handler,
2185 ctx->tc_certdb ) != SECSuccess ) {
2186 PRErrorCode err = PR_GetError();
2187 Debug( LDAP_DEBUG_ANY,
2188 "TLS: error: could not set auth cert handler for moznss - error %d:%s\n",
2189 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2193 if ( SSL_HandshakeCallback( ctx->tc_model, tlsm_handshake_complete_cb, ctx ) ) {
2194 PRErrorCode err = PR_GetError();
2195 Debug( LDAP_DEBUG_ANY,
2196 "TLS: error: could not set handshake callback for moznss - error %d:%s\n",
2197 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2205 tlsm_session *session;
2206 Sockbuf_IO_Desc *sbiod;
2207 /* there seems to be no portable way to determine if the
2208 sockbuf sd has been set to nonblocking mode - the
2209 call to ber_pvt_socket_set_nonblock() takes place
2210 before the tls socket is set up, so we cannot
2211 intercept that call either.
2212 On systems where fcntl is available, we can just
2213 F_GETFL and test for O_NONBLOCK. On other systems,
2214 we will just see if the IO op returns EAGAIN or EWOULDBLOCK,
2215 and just set this flag */
2218 * NSS tries hard to be backwards compatible with SSLv2 clients, or
2219 * clients that send an SSLv2 client hello. This message is not
2220 * tagged in any way, so NSS has no way to know if the incoming
2221 * message is a valid SSLv2 client hello or just some bogus data
2222 * (or cleartext LDAP). We store the first byte read from the
2223 * client here. The most common case will be a client sending
2224 * LDAP data instead of SSL encrypted LDAP data. This can happen,
2225 * for example, if using ldapsearch -Z - if the starttls fails,
2226 * the client will fallback to plain cleartext LDAP. So if we
2227 * see that the firstbyte is a valid LDAP tag, we can be
2228 * pretty sure this is happening.
2232 * NSS doesn't return SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, etc.
2233 * when it is blocked, so we have to set a flag in the wrapped send
2234 * and recv calls that tells us what operation NSS was last blocked
2238 #define TLSM_WRITE 2
2242 static struct tls_data *
2243 tlsm_get_pvt_tls_data( PRFileDesc *fd )
2252 myfd = PR_GetIdentitiesLayer( fd, tlsm_layer_id );
2258 p = (struct tls_data *)myfd->secret;
2264 tlsm_is_non_ssl_message( PRFileDesc *fd, ber_tag_t *thebyte )
2269 *thebyte = LBER_DEFAULT;
2272 p = tlsm_get_pvt_tls_data( fd );
2273 if ( p == NULL || p->sbiod == NULL ) {
2277 if ( p->firsttag == LBER_SEQUENCE ) {
2279 *thebyte = p->firsttag;
2287 static tls_session *
2288 tlsm_session_new ( tls_ctx * ctx, int is_server )
2290 tlsm_ctx *c = (tlsm_ctx *)ctx;
2291 tlsm_session *session;
2296 c->tc_is_server = is_server;
2297 status = PR_CallOnceWithArg( &c->tc_callonce, tlsm_deferred_ctx_init, c );
2298 if ( PR_SUCCESS != status ) {
2299 PRErrorCode err = PR_GetError();
2300 Debug( LDAP_DEBUG_ANY,
2301 "TLS: error: could not initialize moznss security context - error %d:%s\n",
2302 err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT), NULL );
2306 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
2311 session = SSL_ImportFD( c->tc_model, fd );
2318 /* 0 means use the defaults here */
2319 SSL_ConfigServerSessionIDCache( 0, 0, 0, NULL );
2322 rc = SSL_ResetHandshake( session, is_server );
2324 PRErrorCode err = PR_GetError();
2325 Debug( LDAP_DEBUG_TRACE,
2326 "TLS: error: new session - reset handshake failure %d - error %d:%s\n",
2328 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
2330 PR_Close( session );
2334 return (tls_session *)session;
2338 tlsm_session_accept_or_connect( tls_session *session, int is_accept )
2340 tlsm_session *s = (tlsm_session *)session;
2341 int rc = SSL_ForceHandshake( s );
2342 const char *op = is_accept ? "accept" : "connect";
2345 PRErrorCode err = PR_GetError();
2347 if ( err == PR_WOULD_BLOCK_ERROR ) {
2348 ber_tag_t thetag = LBER_DEFAULT;
2349 /* see if we are blocked because of a bogus packet */
2350 if ( tlsm_is_non_ssl_message( s, &thetag ) ) { /* see if we received a non-SSL message */
2351 Debug( LDAP_DEBUG_ANY,
2352 "TLS: error: %s - error - received non-SSL message [0x%x]\n",
2353 op, (unsigned int)thetag, 0 );
2354 /* reset error to something more descriptive */
2355 PR_SetError( SSL_ERROR_RX_MALFORMED_HELLO_REQUEST, EPROTO );
2358 Debug( LDAP_DEBUG_ANY,
2359 "TLS: error: %s - force handshake failure: errno %d - moznss error %d\n",
2367 tlsm_session_accept( tls_session *session )
2369 return tlsm_session_accept_or_connect( session, 1 );
2373 tlsm_session_connect( LDAP *ld, tls_session *session )
2375 return tlsm_session_accept_or_connect( session, 0 );
2379 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
2381 int prerror = PR_GetError();
2383 if ( ( prerror == PR_PENDING_INTERRUPT_ERROR ) || ( prerror == PR_WOULD_BLOCK_ERROR ) ) {
2384 tlsm_session *s = (tlsm_session *)session;
2385 struct tls_data *p = tlsm_get_pvt_tls_data( s );
2387 if ( p && ( p->io_flag == TLSM_READ ) ) {
2388 sb->sb_trans_needs_read = 1;
2390 } else if ( p && ( p->io_flag == TLSM_WRITE ) ) {
2391 sb->sb_trans_needs_write = 1;
2400 tlsm_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
2403 int prerror = PR_GetError();
2405 i = PR_GetErrorTextLength();
2407 char *msg = LDAP_MALLOC( i+1 );
2408 PR_GetErrorText( msg );
2409 memcpy( buf, msg, len );
2412 PR_GetErrorText( buf );
2413 } else if ( prerror ) {
2414 i = PR_snprintf( buf, len, "TLS error %d:%s",
2415 prerror, PR_ErrorToString( prerror, PR_LANGUAGE_I_DEFAULT ) );
2418 return ( i > 0 ) ? buf : NULL;
2422 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
2424 tlsm_session *s = (tlsm_session *)session;
2425 CERTCertificate *cert;
2427 cert = SSL_LocalCertificate( s );
2428 if (!cert) return LDAP_INVALID_CREDENTIALS;
2430 der_dn->bv_val = (char *)cert->derSubject.data;
2431 der_dn->bv_len = cert->derSubject.len;
2432 CERT_DestroyCertificate( cert );
2437 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
2439 tlsm_session *s = (tlsm_session *)session;
2440 CERTCertificate *cert;
2442 cert = SSL_PeerCertificate( s );
2443 if (!cert) return LDAP_INVALID_CREDENTIALS;
2445 der_dn->bv_val = (char *)cert->derSubject.data;
2446 der_dn->bv_len = cert->derSubject.len;
2447 CERT_DestroyCertificate( cert );
2451 /* what kind of hostname were we given? */
2457 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
2459 tlsm_session *s = (tlsm_session *)session;
2460 CERTCertificate *cert;
2461 const char *name, *domain = NULL, *ptr;
2462 int ret, ntype = IS_DNS, nlen, dlen;
2463 #ifdef LDAP_PF_INET6
2464 struct in6_addr addr;
2466 struct in_addr addr;
2471 if( ldap_int_hostname &&
2472 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
2474 name = ldap_int_hostname;
2478 nlen = strlen( name );
2480 cert = SSL_PeerCertificate( s );
2482 Debug( LDAP_DEBUG_ANY,
2483 "TLS: unable to get peer certificate.\n",
2485 /* if this was a fatal condition, things would have
2486 * aborted long before now.
2488 return LDAP_SUCCESS;
2491 #ifdef LDAP_PF_INET6
2492 if (name[0] == '[' && strchr(name, ']')) {
2493 char *n2 = ldap_strdup(name+1);
2494 *strchr(n2, ']') = 0;
2495 if (inet_pton(AF_INET6, n2, &addr))
2500 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
2501 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
2503 if (ntype == IS_DNS ) {
2504 domain = strchr( name, '.' );
2506 dlen = nlen - ( domain - name );
2509 ret = LDAP_LOCAL_ERROR;
2511 rv = CERT_FindCertExtension( cert, SEC_OID_X509_SUBJECT_ALT_NAME,
2513 if ( rv == SECSuccess && altname.data ) {
2515 CERTGeneralName *names, *cur;
2517 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
2519 ret = LDAP_NO_MEMORY;
2523 names = cur = CERT_DecodeAltNameExtension(arena, &altname);
2532 if ( !cur->name.other.len ) continue;
2534 host = (char *)cur->name.other.data;
2535 hlen = cur->name.other.len;
2537 if ( cur->type == certDNSName ) {
2538 if ( ntype != IS_DNS ) continue;
2540 /* is this an exact match? */
2541 if ( nlen == hlen && !strncasecmp( name, host, nlen )) {
2546 /* is this a wildcard match? */
2547 if ( domain && host[0] == '*' && host[1] == '.' &&
2548 dlen == hlen-1 && !strncasecmp( domain, host+1, dlen )) {
2552 } else if ( cur->type == certIPAddress ) {
2553 if ( ntype == IS_DNS ) continue;
2555 #ifdef LDAP_PF_INET6
2556 if (ntype == IS_IP6 && hlen != sizeof(struct in6_addr)) {
2560 if (ntype == IS_IP4 && hlen != sizeof(struct in_addr)) {
2563 if (!memcmp(host, &addr, hlen)) {
2568 } while (( cur = CERT_GetNextGeneralName( cur )) != names );
2570 PORT_FreeArena( arena, PR_FALSE );
2571 SECITEM_FreeItem( &altname, PR_FALSE );
2573 /* no altnames matched, try the CN */
2574 if ( ret != LDAP_SUCCESS ) {
2575 /* find the last CN */
2576 CERTRDN *rdn, **rdns;
2577 CERTAVA *lastava = NULL;
2581 rdns = cert->subject.rdns;
2582 while ( rdns && ( rdn = *rdns++ )) {
2583 CERTAVA *ava, **avas = rdn->avas;
2584 while ( avas && ( ava = *avas++ )) {
2585 if ( CERT_GetAVATag( ava ) == SEC_OID_AVA_COMMON_NAME )
2590 SECItem *av = CERT_DecodeAVAValue( &lastava->value );
2592 if ( av->len == nlen && !strncasecmp( name, (char *)av->data, nlen )) {
2594 } else if ( av->data[0] == '*' && av->data[1] == '.' &&
2595 domain && dlen == av->len - 1 && !strncasecmp( name,
2596 (char *)(av->data+1), dlen )) {
2600 if ( len >= sizeof(buf) )
2601 len = sizeof(buf)-1;
2602 memcpy( buf, av->data, len );
2605 SECITEM_FreeItem( av, PR_TRUE );
2608 if ( ret != LDAP_SUCCESS ) {
2609 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
2610 "common name in certificate (%s).\n",
2612 ret = LDAP_CONNECT_ERROR;
2613 if ( ld->ld_error ) {
2614 LDAP_FREE( ld->ld_error );
2616 ld->ld_error = LDAP_STRDUP(
2617 _("TLS: hostname does not match CN in peer certificate"));
2622 CERT_DestroyCertificate( cert );
2627 tlsm_session_strength( tls_session *session )
2629 tlsm_session *s = (tlsm_session *)session;
2632 rc = SSL_SecurityStatus( s, NULL, NULL, NULL, &keySize,
2634 return rc ? 0 : keySize;
2638 * TLS support for LBER Sockbufs
2641 static PRStatus PR_CALLBACK
2642 tlsm_PR_Close(PRFileDesc *fd)
2644 int rc = PR_SUCCESS;
2646 /* we don't need to actually close anything here, just
2647 pop our io layer off the stack */
2648 fd->secret = NULL; /* must have been freed before calling PR_Close */
2650 fd = PR_PopIOLayer( fd, tlsm_layer_id );
2651 /* if we are not the last layer, pass the close along */
2656 rc = fd->methods->close( fd );
2659 /* we are the last layer - just call our dtor */
2666 static PRStatus PR_CALLBACK
2667 tlsm_PR_Shutdown(PRFileDesc *fd, PRShutdownHow how)
2669 int rc = PR_SUCCESS;
2672 rc = PR_Shutdown( fd->lower, how );
2678 static int PR_CALLBACK
2679 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
2680 PRIntervalTime timeout)
2685 if ( buf == NULL || len <= 0 ) return 0;
2687 p = tlsm_get_pvt_tls_data( fd );
2689 if ( p == NULL || p->sbiod == NULL ) {
2693 rc = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
2695 tlsm_map_error( errno );
2696 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2697 p->nonblock = PR_TRUE; /* fd is using non-blocking io */
2698 } else if ( errno ) { /* real error */
2699 Debug( LDAP_DEBUG_TRACE,
2700 "TLS: error: tlsm_PR_Recv returned %d - error %d:%s\n",
2701 rc, errno, STRERROR(errno) );
2703 } else if ( ( rc > 0 ) && ( len > 0 ) && ( p->firsttag == LBER_DEFAULT ) ) {
2704 p->firsttag = (ber_tag_t)*((char *)buf);
2706 p->io_flag = TLSM_READ;
2711 static int PR_CALLBACK
2712 tlsm_PR_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
2713 PRIntervalTime timeout)
2718 if ( buf == NULL || len <= 0 ) return 0;
2720 p = tlsm_get_pvt_tls_data( fd );
2722 if ( p == NULL || p->sbiod == NULL ) {
2726 rc = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
2728 tlsm_map_error( errno );
2729 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2730 p->nonblock = PR_TRUE;
2731 } else if ( errno ) { /* real error */
2732 Debug( LDAP_DEBUG_TRACE,
2733 "TLS: error: tlsm_PR_Send returned %d - error %d:%s\n",
2734 rc, errno, STRERROR(errno) );
2737 p->io_flag = TLSM_WRITE;
2742 static int PR_CALLBACK
2743 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
2745 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2748 static int PR_CALLBACK
2749 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
2751 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2754 static PRStatus PR_CALLBACK
2755 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
2760 p = tlsm_get_pvt_tls_data( fd );
2762 if ( p == NULL || p->sbiod == NULL ) {
2765 len = sizeof(PRNetAddr);
2766 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
2769 static PRStatus PR_CALLBACK
2770 tlsm_PR_GetSocketOption(PRFileDesc *fd, PRSocketOptionData *data)
2773 p = tlsm_get_pvt_tls_data( fd );
2775 if ( p == NULL || data == NULL ) {
2779 /* only the nonblocking option is supported at this time
2780 MozNSS SSL code needs it */
2781 if ( data->option != PR_SockOpt_Nonblocking ) {
2782 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2786 int flags = fcntl( p->sbiod->sbiod_sb->sb_fd, F_GETFL );
2787 data->value.non_blocking = (flags & O_NONBLOCK) ? PR_TRUE : PR_FALSE;
2789 data->value.non_blocking = p->nonblock;
2794 static PRStatus PR_CALLBACK
2797 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2801 static PRFileDesc * PR_CALLBACK
2804 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2808 static PRInt16 PR_CALLBACK
2811 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2815 static PRInt32 PR_CALLBACK
2818 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2822 static PRInt64 PR_CALLBACK
2827 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2832 static const PRIOMethods tlsm_PR_methods = {
2834 tlsm_PR_Close, /* close */
2835 tlsm_PR_Read, /* read */
2836 tlsm_PR_Write, /* write */
2837 tlsm_PR_i32_unimp, /* available */
2838 tlsm_PR_i64_unimp, /* available64 */
2839 tlsm_PR_prs_unimp, /* fsync */
2840 tlsm_PR_i32_unimp, /* seek */
2841 tlsm_PR_i64_unimp, /* seek64 */
2842 tlsm_PR_prs_unimp, /* fileInfo */
2843 tlsm_PR_prs_unimp, /* fileInfo64 */
2844 tlsm_PR_i32_unimp, /* writev */
2845 tlsm_PR_prs_unimp, /* connect */
2846 tlsm_PR_pfd_unimp, /* accept */
2847 tlsm_PR_prs_unimp, /* bind */
2848 tlsm_PR_prs_unimp, /* listen */
2849 (PRShutdownFN)tlsm_PR_Shutdown, /* shutdown */
2850 tlsm_PR_Recv, /* recv */
2851 tlsm_PR_Send, /* send */
2852 tlsm_PR_i32_unimp, /* recvfrom */
2853 tlsm_PR_i32_unimp, /* sendto */
2854 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
2855 tlsm_PR_i32_unimp, /* acceptread */
2856 tlsm_PR_i32_unimp, /* transmitfile */
2857 tlsm_PR_prs_unimp, /* getsockname */
2858 tlsm_PR_GetPeerName, /* getpeername */
2859 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
2860 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
2861 tlsm_PR_GetSocketOption, /* getsocketoption */
2862 tlsm_PR_i32_unimp, /* setsocketoption */
2863 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
2864 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
2865 tlsm_PR_i32_unimp, /* reserved for future use */
2866 tlsm_PR_i32_unimp, /* reserved for future use */
2867 tlsm_PR_i32_unimp, /* reserved for future use */
2868 tlsm_PR_i32_unimp /* reserved for future use */
2872 * Initialize TLS subsystem. Should be called only once.
2873 * See tlsm_deferred_init for the bulk of the init process
2878 char *nofork = PR_GetEnv( "NSS_STRICT_NOFORK" );
2882 tlsm_layer_id = PR_GetUniqueIdentity( "OpenLDAP" );
2885 * There are some applications that acquire a crypto context in the parent process
2886 * and expect that crypto context to work after a fork(). This does not work
2887 * with NSS using strict PKCS11 compliance mode. We set this environment
2888 * variable here to tell the software encryption module/token to allow crypto
2889 * contexts to persist across a fork(). However, if you are using some other
2890 * module or encryption device that supports and expects full PKCS11 semantics,
2891 * the only recourse is to rewrite the application with atfork() handlers to save
2892 * the crypto context in the parent and restore (and SECMOD_RestartModules) the
2893 * context in the child.
2896 /* will leak one time */
2897 char *noforkenvvar = PL_strdup( "NSS_STRICT_NOFORK=DISABLED" );
2898 PR_SetEnv( noforkenvvar );
2905 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
2908 tlsm_session *session = arg;
2911 assert( sbiod != NULL );
2913 p = LBER_MALLOC( sizeof( *p ) );
2918 fd = PR_GetIdentitiesLayer( session, tlsm_layer_id );
2924 fd->secret = (PRFilePrivate *)p;
2925 p->session = session;
2927 p->firsttag = LBER_DEFAULT;
2928 sbiod->sbiod_pvt = p;
2933 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
2937 assert( sbiod != NULL );
2938 assert( sbiod->sbiod_pvt != NULL );
2940 p = (struct tls_data *)sbiod->sbiod_pvt;
2941 PR_Close( p->session );
2942 LBER_FREE( sbiod->sbiod_pvt );
2943 sbiod->sbiod_pvt = NULL;
2948 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
2952 assert( sbiod != NULL );
2953 assert( sbiod->sbiod_pvt != NULL );
2955 p = (struct tls_data *)sbiod->sbiod_pvt;
2956 PR_Shutdown( p->session, PR_SHUTDOWN_BOTH );
2961 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
2965 assert( sbiod != NULL );
2966 assert( sbiod->sbiod_pvt != NULL );
2968 p = (struct tls_data *)sbiod->sbiod_pvt;
2970 if ( opt == LBER_SB_OPT_GET_SSL ) {
2971 *((tlsm_session **)arg) = p->session;
2974 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
2975 if ( p && ( SSL_DataPending( p->session ) > 0 ) ) {
2981 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
2985 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2991 assert( sbiod != NULL );
2992 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2994 p = (struct tls_data *)sbiod->sbiod_pvt;
2996 ret = PR_Recv( p->session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2998 err = PR_GetError();
2999 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
3000 sbiod->sbiod_sb->sb_trans_needs_read = 1;
3001 sock_errset(EWOULDBLOCK);
3004 sbiod->sbiod_sb->sb_trans_needs_read = 0;
3010 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
3016 assert( sbiod != NULL );
3017 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
3019 p = (struct tls_data *)sbiod->sbiod_pvt;
3021 ret = PR_Send( p->session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
3023 err = PR_GetError();
3024 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
3025 sbiod->sbiod_sb->sb_trans_needs_write = 1;
3026 sock_errset(EWOULDBLOCK);
3030 sbiod->sbiod_sb->sb_trans_needs_write = 0;
3035 static Sockbuf_IO tlsm_sbio =
3037 tlsm_sb_setup, /* sbi_setup */
3038 tlsm_sb_remove, /* sbi_remove */
3039 tlsm_sb_ctrl, /* sbi_ctrl */
3040 tlsm_sb_read, /* sbi_read */
3041 tlsm_sb_write, /* sbi_write */
3042 tlsm_sb_close /* sbi_close */
3045 tls_impl ldap_int_tls_impl = {
3057 tlsm_session_connect,
3058 tlsm_session_accept,
3059 tlsm_session_upflags,
3060 tlsm_session_errmsg,
3062 tlsm_session_peer_dn,
3063 tlsm_session_chkhost,
3064 tlsm_session_strength,
3068 #ifdef LDAP_R_COMPILE
3077 #endif /* HAVE_MOZNSS */