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>
46 #include <ldap_pvt_thread.h>
49 #define READ_PASSWORD_FROM_STDIN
50 #define READ_PASSWORD_FROM_FILE
52 #ifdef READ_PASSWORD_FROM_STDIN
53 #include <termios.h> /* for echo on/off */
56 #include <nspr/nspr.h>
57 #include <nspr/private/pprio.h>
60 #include <nss/sslerr.h>
61 #include <nss/sslproto.h>
62 #include <nss/pk11pub.h>
63 #include <nss/secerr.h>
64 #include <nss/keyhi.h>
65 #include <nss/secmod.h>
68 /* NSS 3.12.5 and later have NSS_InitContext */
69 #if NSS_VMAJOR <= 3 && NSS_VMINOR <= 12 && NSS_VPATCH < 5
72 #define HAVE_NSS_INITCONTEXT 1
75 /* InitContext does not currently work in server mode */
76 /* #define INITCONTEXT_HACK 1 */
78 typedef struct tlsm_ctx {
81 PRBool tc_verify_cert;
82 CERTCertDBHandle *tc_certdb;
85 struct ldaptls *tc_config;
88 PRCallOnceType tc_callonce;
90 char *tc_slotname; /* if using pem */
91 #ifdef HAVE_NSS_INITCONTEXT
92 NSSInitContext *tc_initctx; /* the NSS context */
94 PK11GenericObject **tc_pem_objs; /* array of objects to free */
95 int tc_n_pem_objs; /* number of objects */
97 ldap_pvt_thread_mutex_t tc_refmutex;
101 typedef PRFileDesc tlsm_session;
103 static PRDescIdentity tlsm_layer_id;
105 static const PRIOMethods tlsm_PR_methods;
107 #define PEM_LIBRARY "nsspem"
108 #define PEM_MODULE "PEM"
109 /* hash files for use with cacertdir have this file name suffix */
110 #define PEM_CA_HASH_FILE_SUFFIX ".0"
111 #define PEM_CA_HASH_FILE_SUFFIX_LEN 2
113 static SECMODModule *pem_module;
115 #define DEFAULT_TOKEN_NAME "default"
116 /* sprintf format used to create token name */
117 #define TLSM_PEM_TOKEN_FMT "PEM Token #%ld"
119 static int tlsm_slot_count;
121 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
122 (x)->pValue=(v); (x)->ulValueLen = (l);
124 /* forward declaration */
125 static int tlsm_init( void );
127 #ifdef LDAP_R_COMPILE
130 tlsm_thr_init( void )
134 #endif /* LDAP_R_COMPILE */
137 tlsm_dump_cipher_info(PRFileDesc *fd)
141 for (ii = 0; ii < SSL_NumImplementedCiphers; ++ii) {
142 PRInt32 cipher = (PRInt32)SSL_ImplementedCiphers[ii];
143 PRBool enabled = PR_FALSE;
145 SSLCipherSuiteInfo info;
148 SSL_CipherPrefGet(fd, cipher, &enabled);
150 SSL_CipherPrefGetDefault(cipher, &enabled);
152 SSL_CipherPolicyGet(cipher, &policy);
153 SSL_GetCipherSuiteInfo(cipher, &info, (PRUintn)sizeof(info));
154 Debug( LDAP_DEBUG_TRACE,
155 "TLS: cipher: %d - %s, enabled: %d, ",
156 info.cipherSuite, info.cipherSuiteName, enabled );
157 Debug( LDAP_DEBUG_TRACE,
158 "policy: %d\n", policy, 0, 0 );
164 /* Cipher definitions */
166 char *ossl_name; /* The OpenSSL cipher name */
167 int num; /* The cipher id */
168 int attr; /* cipher attributes: algorithms, etc */
169 int version; /* protocol version valid for this cipher */
170 int bits; /* bits of strength */
171 int alg_bits; /* bits of the algorithm */
172 int strength; /* LOW, MEDIUM, HIGH */
173 int enabled; /* Enabled by default? */
176 /* cipher attributes */
177 #define SSL_kRSA 0x00000001L
178 #define SSL_aRSA 0x00000002L
179 #define SSL_aDSS 0x00000004L
180 #define SSL_DSS SSL_aDSS
181 #define SSL_eNULL 0x00000008L
182 #define SSL_DES 0x00000010L
183 #define SSL_3DES 0x00000020L
184 #define SSL_RC4 0x00000040L
185 #define SSL_RC2 0x00000080L
186 #define SSL_AES 0x00000100L
187 #define SSL_MD5 0x00000200L
188 #define SSL_SHA1 0x00000400L
189 #define SSL_SHA SSL_SHA1
190 #define SSL_RSA (SSL_kRSA|SSL_aRSA)
192 /* cipher strength */
193 #define SSL_NULL 0x00000001L
194 #define SSL_EXPORT40 0x00000002L
195 #define SSL_EXPORT56 0x00000004L
196 #define SSL_LOW 0x00000008L
197 #define SSL_MEDIUM 0x00000010L
198 #define SSL_HIGH 0x00000020L
200 #define SSL2 0x00000001L
201 #define SSL3 0x00000002L
202 /* OpenSSL treats SSL3 and TLSv1 the same */
205 /* Cipher translation */
206 static cipher_properties ciphers_def[] = {
208 {"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},
209 {"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},
210 {"RC4-MD5", SSL_EN_RC4_128_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
211 {"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},
212 {"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},
213 {"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},
216 {"RC4-MD5", SSL_RSA_WITH_RC4_128_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
217 {"RC4-SHA", SSL_RSA_WITH_RC4_128_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA1, SSL3, 128, 128, SSL_MEDIUM, SSL_NOT_ALLOWED},
218 {"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},
219 {"DES-CBC-SHA", SSL_RSA_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA1, SSL3, 56, 56, SSL_LOW, SSL_ALLOWED},
220 {"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},
221 {"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},
222 {"NULL-MD5", SSL_RSA_WITH_NULL_MD5, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_MD5, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
223 {"NULL-SHA", SSL_RSA_WITH_NULL_SHA, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_SHA1, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
226 {"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},
227 {"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},
228 {"AES128-SHA", TLS_RSA_WITH_AES_128_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_AES|SSL_SHA, TLS1, 128, 128, SSL_HIGH, SSL_NOT_ALLOWED},
229 {"AES256-SHA", TLS_RSA_WITH_AES_256_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_AES|SSL_SHA, TLS1, 256, 256, SSL_HIGH, SSL_NOT_ALLOWED},
232 #define ciphernum (sizeof(ciphers_def)/sizeof(cipher_properties))
234 /* given err which is the current errno, calls PR_SetError with
235 the corresponding NSPR error code */
237 tlsm_map_error(int err)
243 prError = PR_NO_ACCESS_RIGHTS_ERROR;
246 prError = PR_ADDRESS_IN_USE_ERROR;
249 prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
252 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
255 prError = PR_WOULD_BLOCK_ERROR;
258 * On QNX and Neutrino, EALREADY is defined as EBUSY.
260 #if EALREADY != EBUSY
262 prError = PR_ALREADY_INITIATED_ERROR;
266 prError = PR_BAD_DESCRIPTOR_ERROR;
270 prError = PR_IO_ERROR;
274 prError = PR_FILESYSTEM_MOUNTED_ERROR;
277 prError = PR_CONNECT_ABORTED_ERROR;
280 prError = PR_CONNECT_REFUSED_ERROR;
283 prError = PR_CONNECT_RESET_ERROR;
286 prError = PR_DEADLOCK_ERROR;
290 prError = PR_DIRECTORY_CORRUPTED_ERROR;
295 prError = PR_NO_DEVICE_SPACE_ERROR;
299 prError = PR_FILE_EXISTS_ERROR;
302 prError = PR_ACCESS_FAULT_ERROR;
305 prError = PR_FILE_TOO_BIG_ERROR;
308 prError = PR_HOST_UNREACHABLE_ERROR;
311 prError = PR_IN_PROGRESS_ERROR;
314 prError = PR_PENDING_INTERRUPT_ERROR;
317 prError = PR_INVALID_ARGUMENT_ERROR;
320 prError = PR_IO_ERROR;
323 prError = PR_IS_CONNECTED_ERROR;
326 prError = PR_IS_DIRECTORY_ERROR;
329 prError = PR_LOOP_ERROR;
332 prError = PR_PROC_DESC_TABLE_FULL_ERROR;
335 prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
338 prError = PR_INVALID_ARGUMENT_ERROR;
342 prError = PR_REMOTE_FILE_ERROR;
346 prError = PR_NAME_TOO_LONG_ERROR;
349 prError = PR_NETWORK_UNREACHABLE_ERROR;
352 prError = PR_SYS_DESC_TABLE_FULL_ERROR;
355 * On SCO OpenServer 5, ENOBUFS is defined as ENOSR.
357 #if defined(ENOBUFS) && (ENOBUFS != ENOSR)
359 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
363 prError = PR_FILE_NOT_FOUND_ERROR;
366 prError = PR_FILE_NOT_FOUND_ERROR;
369 prError = PR_FILE_IS_LOCKED_ERROR;
373 prError = PR_REMOTE_FILE_ERROR;
377 prError = PR_OUT_OF_MEMORY_ERROR;
380 prError = PR_INVALID_ARGUMENT_ERROR;
383 prError = PR_NO_DEVICE_SPACE_ERROR;
387 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
391 prError = PR_NOT_CONNECTED_ERROR;
394 prError = PR_NOT_DIRECTORY_ERROR;
397 prError = PR_NOT_SOCKET_ERROR;
400 prError = PR_FILE_NOT_FOUND_ERROR;
403 prError = PR_NOT_TCP_SOCKET_ERROR;
407 prError = PR_BUFFER_OVERFLOW_ERROR;
411 prError = PR_NO_ACCESS_RIGHTS_ERROR;
414 prError = PR_CONNECT_RESET_ERROR;
418 prError = PR_IO_ERROR;
421 case EPROTONOSUPPORT:
422 prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
425 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
428 prError = PR_INVALID_METHOD_ERROR;
431 prError = PR_READ_ONLY_FILESYSTEM_ERROR;
434 prError = PR_INVALID_METHOD_ERROR;
437 prError = PR_IO_TIMEOUT_ERROR;
439 #if EWOULDBLOCK != EAGAIN
441 prError = PR_WOULD_BLOCK_ERROR;
445 prError = PR_NOT_SAME_DEVICE_ERROR;
448 prError = PR_UNKNOWN_ERROR;
451 PR_SetError( prError, err );
455 * cipher_list is an integer array with the following values:
456 * -1: never enable this cipher
461 nss_parse_ciphers(const char *cipherstr, int cipher_list[ciphernum])
470 /* All disabled to start */
471 for (i=0; i<ciphernum; i++)
474 ciphertip = strdup(cipherstr);
475 cipher = ciphers = ciphertip;
477 while (ciphers && (strlen(ciphers))) {
478 while ((*cipher) && (isspace(*cipher)))
483 case '+': /* Add something */
487 case '-': /* Subtract something */
491 case '!': /* Disable something */
500 if ((ciphers = strchr(cipher, ':'))) {
504 /* Do the easy one first */
505 if (!strcmp(cipher, "ALL")) {
506 for (i=0; i<ciphernum; i++) {
507 if (!(ciphers_def[i].attr & SSL_eNULL))
508 cipher_list[i] = action;
510 } else if (!strcmp(cipher, "COMPLEMENTOFALL")) {
511 for (i=0; i<ciphernum; i++) {
512 if ((ciphers_def[i].attr & SSL_eNULL))
513 cipher_list[i] = action;
515 } else if (!strcmp(cipher, "DEFAULT")) {
516 for (i=0; i<ciphernum; i++) {
517 cipher_list[i] = ciphers_def[i].enabled == SSL_ALLOWED ? 1 : 0;
526 while (c && (strlen(c))) {
528 if ((c = strchr(cipher, '+'))) {
532 if (!strcmp(cipher, "RSA")) {
534 } else if ((!strcmp(cipher, "NULL")) || (!strcmp(cipher, "eNULL"))) {
536 } else if (!strcmp(cipher, "AES")) {
538 } else if (!strcmp(cipher, "3DES")) {
540 } else if (!strcmp(cipher, "DES")) {
542 } else if (!strcmp(cipher, "RC4")) {
544 } else if (!strcmp(cipher, "RC2")) {
546 } else if (!strcmp(cipher, "MD5")) {
548 } else if ((!strcmp(cipher, "SHA")) || (!strcmp(cipher, "SHA1"))) {
550 } else if (!strcmp(cipher, "SSLv2")) {
552 } else if (!strcmp(cipher, "SSLv3")) {
554 } else if (!strcmp(cipher, "TLSv1")) {
556 } else if (!strcmp(cipher, "HIGH")) {
557 strength |= SSL_HIGH;
558 } else if (!strcmp(cipher, "MEDIUM")) {
559 strength |= SSL_MEDIUM;
560 } else if (!strcmp(cipher, "LOW")) {
562 } else if ((!strcmp(cipher, "EXPORT")) || (!strcmp(cipher, "EXP"))) {
563 strength |= SSL_EXPORT40|SSL_EXPORT56;
564 } else if (!strcmp(cipher, "EXPORT40")) {
565 strength |= SSL_EXPORT40;
566 } else if (!strcmp(cipher, "EXPORT56")) {
567 strength |= SSL_EXPORT56;
575 /* If we have a mask, apply it. If not then perhaps they provided
576 * a specific cipher to enable.
578 if (mask || strength || protocol) {
579 for (i=0; i<ciphernum; i++) {
580 if (((ciphers_def[i].attr & mask) ||
581 (ciphers_def[i].strength & strength) ||
582 (ciphers_def[i].version & protocol)) &&
583 (cipher_list[i] != -1)) {
584 /* Enable the NULL ciphers only if explicity
586 if (ciphers_def[i].attr & SSL_eNULL) {
587 if (mask & SSL_eNULL)
588 cipher_list[i] = action;
590 cipher_list[i] = action;
594 for (i=0; i<ciphernum; i++) {
595 if (!strcmp(ciphers_def[i].ossl_name, cipher) &&
596 cipher_list[1] != -1)
597 cipher_list[i] = action;
606 /* See if any ciphers were enabled */
608 for (i=0; i<ciphernum; i++) {
609 if (cipher_list[i] == 1)
619 tlsm_parse_ciphers(tlsm_ctx *ctx, const char *str)
621 int cipher_state[ciphernum];
627 rv = nss_parse_ciphers(str, cipher_state);
630 /* First disable everything */
631 for (i = 0; i < SSL_NumImplementedCiphers; i++)
632 SSL_CipherPrefSet(ctx->tc_model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
634 /* Now enable what was requested */
635 for (i=0; i<ciphernum; i++) {
636 SSLCipherSuiteInfo suite;
639 if (SSL_GetCipherSuiteInfo(ciphers_def[i].num, &suite, sizeof suite)
641 enabled = cipher_state[i] < 0 ? 0 : cipher_state[i];
642 if (enabled == SSL_ALLOWED) {
643 if (PK11_IsFIPS() && !suite.isFIPS)
644 enabled = SSL_NOT_ALLOWED;
646 SSL_CipherPrefSet(ctx->tc_model, ciphers_def[i].num, enabled);
651 return rv == 1 ? 0 : -1;
655 tlsm_bad_cert_handler(void *arg, PRFileDesc *ssl)
657 SECStatus success = SECSuccess;
659 tlsm_ctx *ctx = (tlsm_ctx *)arg;
665 err = PORT_GetError();
668 case SEC_ERROR_UNTRUSTED_ISSUER:
669 case SEC_ERROR_UNKNOWN_ISSUER:
670 case SEC_ERROR_EXPIRED_CERTIFICATE:
671 if (ctx->tc_verify_cert) {
672 success = SECFailure;
675 /* we bypass NSS's hostname checks and do our own */
676 case SSL_ERROR_BAD_CERT_DOMAIN:
679 success = SECFailure;
687 tlsm_dump_security_status(PRFileDesc *fd)
689 char * cp; /* bulk cipher name */
690 char * ip; /* cert issuer DN */
691 char * sp; /* cert subject DN */
692 int op; /* High, Low, Off */
693 int kp0; /* total key bits */
694 int kp1; /* secret key bits */
695 SSL3Statistics * ssl3stats = SSL_GetStatistics();
697 SSL_SecurityStatus( fd, &op, &cp, &kp0, &kp1, &ip, &sp );
698 Debug( LDAP_DEBUG_TRACE,
699 "TLS certificate verification: subject: %s, issuer: %s, cipher: %s, ",
700 sp ? sp : "-unknown-", ip ? ip : "-unknown-", cp ? cp : "-unknown-" );
704 Debug( LDAP_DEBUG_TRACE,
705 "security level: %s, secret key bits: %d, total key bits: %d, ",
706 ((op == SSL_SECURITY_STATUS_ON_HIGH) ? "high" :
707 ((op == SSL_SECURITY_STATUS_ON_LOW) ? "low" : "off")),
710 Debug( LDAP_DEBUG_TRACE,
711 "cache hits: %ld, cache misses: %ld, cache not reusable: %ld\n",
712 ssl3stats->hch_sid_cache_hits, ssl3stats->hch_sid_cache_misses,
713 ssl3stats->hch_sid_cache_not_ok );
719 tlsm_handshake_complete_cb( PRFileDesc *fd, void *client_data )
721 tlsm_dump_security_status( fd );
724 #ifdef READ_PASSWORD_FROM_FILE
726 tlsm_get_pin_from_file(const char *token_name, tlsm_ctx *ctx)
729 char *contents = NULL;
732 char *candidate = NULL;
733 PRFileInfo file_info;
734 PRFileDesc *pwd_fileptr = PR_Open( ctx->tc_pin_file, PR_RDONLY, 00400 );
736 /* open the password file */
737 if ( !pwd_fileptr ) {
738 PRErrorCode errcode = PR_GetError();
739 Debug( LDAP_DEBUG_ANY,
740 "TLS: could not open security pin file %s - error %d:%s.\n",
741 ctx->tc_pin_file, errcode,
742 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
746 /* get the file size */
747 if ( PR_SUCCESS != PR_GetFileInfo( ctx->tc_pin_file, &file_info ) ) {
748 PRErrorCode errcode = PR_GetError();
749 Debug( LDAP_DEBUG_ANY,
750 "TLS: could not get file info from pin file %s - error %d:%s.\n",
751 ctx->tc_pin_file, errcode,
752 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
756 /* create a buffer to hold the file contents */
757 if ( !( contents = PR_MALLOC( file_info.size + 1 ) ) ) {
758 PRErrorCode errcode = PR_GetError();
759 Debug( LDAP_DEBUG_ANY,
760 "TLS: could not alloc a buffer for contents of pin file %s - error %d:%s.\n",
761 ctx->tc_pin_file, errcode,
762 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
766 /* read file into the buffer */
767 if( PR_Read( pwd_fileptr, contents, file_info.size ) <= 0 ) {
768 PRErrorCode errcode = PR_GetError();
769 Debug( LDAP_DEBUG_ANY,
770 "TLS: could not read the file contents from pin file %s - error %d:%s.\n",
771 ctx->tc_pin_file, errcode,
772 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
776 /* format is [tokenname:]password EOL [tokenname:]password EOL ... */
777 /* if you want to use a password containing a colon character, use
778 the special tokenname "default" */
779 for ( line = PL_strtok_r( contents, "\r\n", &lasts ); line;
780 line = PL_strtok_r( NULL, "\r\n", &lasts ) ) {
784 continue; /* skip blank lines */
786 colon = PL_strchr( line, ':' );
788 if ( *(colon + 1) && token_name &&
789 !PL_strncmp( token_name, line, colon-line ) ) {
790 candidate = colon + 1; /* found a definite match */
792 } else if ( !PL_strncmp( DEFAULT_TOKEN_NAME, line, colon-line ) ) {
793 candidate = colon + 1; /* found possible match */
795 } else { /* no token name */
801 PR_Close( pwd_fileptr );
804 pwdstr = PL_strdup( candidate );
806 PL_strfree( contents );
810 #endif /* READ_PASSWORD_FROM_FILE */
812 #ifdef READ_PASSWORD_FROM_STDIN
814 * Turn the echoing off on a tty.
819 if ( isatty( fd ) ) {
821 tcgetattr( fd, &tio );
822 tio.c_lflag &= ~ECHO;
823 tcsetattr( fd, TCSAFLUSH, &tio );
828 * Turn the echoing on on a tty.
833 if ( isatty( fd ) ) {
835 tcgetattr( fd, &tio );
837 tcsetattr( fd, TCSAFLUSH, &tio );
838 tcsetattr( fd, TCSAFLUSH, &tio );
841 #endif /* READ_PASSWORD_FROM_STDIN */
844 * This does the actual work of reading the pin/password/pass phrase
847 tlsm_get_pin(PK11SlotInfo *slot, PRBool retry, tlsm_ctx *ctx)
849 char *token_name = NULL;
852 token_name = PK11_GetTokenName( slot );
853 #ifdef READ_PASSWORD_FROM_FILE
854 /* Try to get the passwords from the password file if it exists.
855 * THIS IS UNSAFE and is provided for convenience only. Without this
856 * capability the server would have to be started in foreground mode
857 * if using an encrypted key.
859 if ( ctx->tc_pin_file ) {
860 pwdstr = tlsm_get_pin_from_file( token_name, ctx );
862 #endif /* RETRIEVE_PASSWORD_FROM_FILE */
863 #ifdef READ_PASSWORD_FROM_STDIN
865 int infd = PR_FileDesc2NativeHandle( PR_STDIN );
866 int isTTY = isatty( infd );
867 unsigned char phrase[200];
868 /* Prompt for password */
871 "Please enter pin, password, or pass phrase for security token '%s': ",
872 token_name ? token_name : DEFAULT_TOKEN_NAME );
875 fgets( (char*)phrase, sizeof(phrase), stdin );
877 fprintf( stdout, "\n" );
880 /* stomp on newline */
881 phrase[strlen((char*)phrase)-1] = 0;
883 pwdstr = PL_strdup( (char*)phrase );
886 #endif /* READ_PASSWORD_FROM_STDIN */
891 * PKCS11 devices (including the internal softokn cert/key database)
892 * may be protected by a pin or password or even pass phrase
893 * MozNSS needs a way for the user to provide that
896 tlsm_pin_prompt(PK11SlotInfo *slot, PRBool retry, void *arg)
898 tlsm_ctx *ctx = (tlsm_ctx *)arg;
900 return tlsm_get_pin( slot, retry, ctx );
904 tlsm_get_basic_constraint_extension( CERTCertificate *cert,
905 CERTBasicConstraints *cbcval )
907 SECItem encodedVal = { 0, NULL };
910 rc = CERT_FindCertExtension( cert, SEC_OID_X509_BASIC_CONSTRAINTS,
912 if ( rc != SECSuccess ) {
916 rc = CERT_DecodeBasicConstraintValue( cbcval, &encodedVal );
918 /* free the raw extension data */
919 PORT_Free( encodedVal.data );
925 tlsm_cert_is_self_issued( CERTCertificate *cert )
927 /* A cert is self-issued if its subject and issuer are equal and
928 * both are of non-zero length.
930 PRBool is_self_issued = cert &&
931 (PRBool)SECITEM_ItemsAreEqual( &cert->derIssuer,
932 &cert->derSubject ) &&
933 cert->derSubject.len > 0;
934 return is_self_issued;
938 tlsm_verify_cert(CERTCertDBHandle *handle, CERTCertificate *cert, void *pinarg,
939 PRBool checksig, SECCertUsage certUsage, int errorToIgnore )
941 CERTVerifyLog verifylog;
942 SECStatus ret = SECSuccess;
945 /* the log captures information about every cert in the chain, so we can tell
946 which cert caused the problem and what the problem was */
947 memset( &verifylog, 0, sizeof( verifylog ) );
948 verifylog.arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE );
949 if ( verifylog.arena == NULL ) {
950 Debug( LDAP_DEBUG_ANY,
951 "TLS certificate verification: Out of memory for certificate verification logger\n",
955 ret = CERT_VerifyCertificate( handle, cert, checksig, certUsage, PR_Now(), pinarg, &verifylog,
957 if ( ( name = cert->subjectName ) == NULL ) {
958 name = cert->nickname;
960 if ( verifylog.head == NULL ) {
961 /* it is possible for CERT_VerifyCertificate return with an error with no logging */
962 if ( ret != SECSuccess ) {
963 PRErrorCode errcode = PR_GetError();
964 Debug( LDAP_DEBUG_ANY,
965 "TLS: certificate [%s] is not valid - error %d:%s.\n",
966 name ? name : "(unknown)",
967 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
971 CERTVerifyLogNode *node;
973 ret = SECSuccess; /* reset */
974 node = verifylog.head;
976 if ( ( name = node->cert->subjectName ) == NULL ) {
977 name = node->cert->nickname;
980 /* NSS does not like CA certs that have the basic constraints extension
981 with the CA flag set to FALSE - openssl doesn't check if the cert
983 if ( ( node->error == SEC_ERROR_CA_CERT_INVALID ) &&
984 tlsm_cert_is_self_issued( node->cert ) ) {
985 CERTBasicConstraints basicConstraint;
986 SECStatus rv = tlsm_get_basic_constraint_extension( node->cert, &basicConstraint );
987 if ( ( rv == SECSuccess ) && ( basicConstraint.isCA == PR_FALSE ) ) {
988 Debug( LDAP_DEBUG_TRACE,
989 "TLS: certificate [%s] is not correct because it is a CA cert and the "
990 "BasicConstraint CA flag is set to FALSE - allowing for now, but "
991 "please fix your certs if possible\n", name, 0, 0 );
992 } else { /* does not have basicconstraint, or some other error */
994 Debug( LDAP_DEBUG_ANY,
995 "TLS: certificate [%s] is not valid - CA cert is not valid\n",
998 } else if ( errorToIgnore && ( node->error == errorToIgnore ) ) {
999 Debug( LDAP_DEBUG_ANY,
1000 "TLS: Warning: ignoring error for certificate [%s] - error %ld:%s.\n",
1001 name, node->error, PR_ErrorToString( node->error, PR_LANGUAGE_I_DEFAULT ) );
1004 Debug( LDAP_DEBUG_ANY,
1005 "TLS: certificate [%s] is not valid - error %ld:%s.\n",
1006 name, node->error, PR_ErrorToString( node->error, PR_LANGUAGE_I_DEFAULT ) );
1009 CERT_DestroyCertificate( node->cert );
1014 PORT_FreeArena( verifylog.arena, PR_FALSE );
1016 if ( ret == SECSuccess ) {
1017 Debug( LDAP_DEBUG_TRACE,
1018 "TLS: certificate [%s] is valid\n", name, 0, 0 );
1025 tlsm_auth_cert_handler(void *arg, PRFileDesc *fd,
1026 PRBool checksig, PRBool isServer)
1028 SECCertUsage certUsage = isServer ? certUsageSSLClient : certUsageSSLServer;
1029 SECStatus ret = SECSuccess;
1031 ret = tlsm_verify_cert( (CERTCertDBHandle *)arg, SSL_PeerCertificate( fd ),
1032 SSL_RevealPinArg( fd ),
1033 checksig, certUsage, 0 );
1039 tlsm_authenticate_to_slot( tlsm_ctx *ctx, PK11SlotInfo *slot )
1043 if ( SECSuccess != PK11_Authenticate( slot, PR_FALSE, ctx ) ) {
1044 char *token_name = PK11_GetTokenName( slot );
1045 PRErrorCode errcode = PR_GetError();
1046 Debug( LDAP_DEBUG_ANY,
1047 "TLS: could not authenticate to the security token %s - error %d:%s.\n",
1048 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1049 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1051 rc = 0; /* success */
1058 tlsm_nss_shutdown_cb( void *appData, void *nssData )
1060 SECStatus rc = SECSuccess;
1062 SSL_ShutdownServerSessionIDCache();
1063 SSL_ClearSessionCache();
1066 SECMOD_UnloadUserModule( pem_module );
1067 SECMOD_DestroyModule( pem_module );
1074 tlsm_init_pem_module( void )
1077 char *fullname = NULL;
1078 char *configstring = NULL;
1084 /* not loaded - load it */
1085 /* get the system dependent library name */
1086 fullname = PR_GetLibraryName( NULL, PEM_LIBRARY );
1087 /* Load our PKCS#11 module */
1088 configstring = PR_smprintf( "library=%s name=" PEM_MODULE " parameters=\"\"", fullname );
1089 PL_strfree( fullname );
1091 pem_module = SECMOD_LoadUserModule( configstring, NULL, PR_FALSE );
1092 PR_smprintf_free( configstring );
1094 if ( !pem_module || !pem_module->loaded ) {
1096 SECMOD_DestroyModule( pem_module );
1106 tlsm_add_pem_obj( tlsm_ctx *ctx, PK11GenericObject *obj )
1108 int idx = ctx->tc_n_pem_objs;
1109 ctx->tc_n_pem_objs++;
1110 ctx->tc_pem_objs = (PK11GenericObject **)
1111 PORT_Realloc( ctx->tc_pem_objs, ctx->tc_n_pem_objs * sizeof( PK11GenericObject * ) );
1112 ctx->tc_pem_objs[idx] = obj;
1116 tlsm_free_pem_objs( tlsm_ctx *ctx )
1118 /* free in reverse order of allocation */
1119 while ( ctx->tc_n_pem_objs-- ) {
1120 PK11_DestroyGenericObject( ctx->tc_pem_objs[ctx->tc_n_pem_objs] );
1121 ctx->tc_pem_objs[ctx->tc_n_pem_objs] = NULL;
1123 PORT_Free(ctx->tc_pem_objs);
1124 ctx->tc_pem_objs = NULL;
1125 ctx->tc_n_pem_objs = 0;
1129 tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca, PRBool istrusted )
1132 PK11SlotInfo *slot = NULL;
1133 PK11GenericObject *rv;
1134 CK_ATTRIBUTE *attrs;
1135 CK_ATTRIBUTE theTemplate[20];
1136 CK_BBOOL cktrue = CK_TRUE;
1137 CK_BBOOL ckfalse = CK_FALSE;
1138 CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
1139 char tmpslotname[64];
1140 char *slotname = NULL;
1141 const char *ptr = NULL;
1142 char sep = PR_GetDirectorySeparator();
1146 memset( &fi, 0, sizeof(fi) );
1147 status = PR_GetFileInfo( filename, &fi );
1148 if ( PR_SUCCESS != status) {
1149 PRErrorCode errcode = PR_GetError();
1150 Debug( LDAP_DEBUG_ANY,
1151 "TLS: could not read certificate file %s - error %d:%s.\n",
1153 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1157 if ( fi.type != PR_FILE_FILE ) {
1158 PR_SetError(PR_IS_DIRECTORY_ERROR, 0);
1159 Debug( LDAP_DEBUG_ANY,
1160 "TLS: error: the certificate file %s is not a file.\n",
1165 attrs = theTemplate;
1168 slotID = 0; /* CA and trust objects use slot 0 */
1169 PR_snprintf( tmpslotname, sizeof(tmpslotname), TLSM_PEM_TOKEN_FMT, slotID );
1170 slotname = tmpslotname;
1171 istrusted = PR_TRUE;
1173 if ( ctx->tc_slotname == NULL ) { /* need new slot */
1177 slotID = ++tlsm_slot_count;
1179 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
1181 slotname = ctx->tc_slotname;
1183 if ( ( ptr = PL_strrchr( filename, sep ) ) ) {
1184 PL_strfree( ctx->tc_certname );
1187 /* pemnss conflates trusted certs with CA certs - since there can
1188 be more than one CA cert in a file (e.g. ca-bundle.crt) pemnss
1189 numbers each trusted cert - in the case of a server cert, there will be
1190 only one, so it will be number 0 */
1191 ctx->tc_certname = PR_smprintf( "%s:%s - 0", slotname, ptr );
1193 ctx->tc_certname = PR_smprintf( "%s:%s", slotname, ptr );
1198 slot = PK11_FindSlotByName( slotname );
1201 PRErrorCode errcode = PR_GetError();
1202 Debug( LDAP_DEBUG_ANY,
1203 "TLS: could not find the slot for certificate %s - error %d:%s.\n",
1204 ctx->tc_certname, errcode,
1205 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1209 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1210 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1211 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1213 PK11_SETATTRS( attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1215 PK11_SETATTRS( attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) ); attrs++;
1217 /* This loads the certificate in our PEM module into the appropriate
1220 rv = PK11_CreateGenericObject( slot, theTemplate, 4, PR_FALSE /* isPerm */ );
1222 PK11_FreeSlot( slot );
1225 PRErrorCode errcode = PR_GetError();
1226 Debug( LDAP_DEBUG_ANY,
1227 "TLS: could not add the certificate %s - error %d:%s.\n",
1228 ctx->tc_certname, errcode,
1229 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1233 tlsm_add_pem_obj( ctx, rv );
1239 tlsm_add_key_from_file( tlsm_ctx *ctx, const char *filename )
1242 PK11SlotInfo * slot = NULL;
1243 PK11GenericObject *rv;
1244 CK_ATTRIBUTE *attrs;
1245 CK_ATTRIBUTE theTemplate[20];
1246 CK_BBOOL cktrue = CK_TRUE;
1247 CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
1252 memset( &fi, 0, sizeof(fi) );
1253 status = PR_GetFileInfo( filename, &fi );
1254 if ( PR_SUCCESS != status) {
1255 PRErrorCode errcode = PR_GetError();
1256 Debug( LDAP_DEBUG_ANY,
1257 "TLS: could not read key file %s - error %d:%s.\n",
1259 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1263 if ( fi.type != PR_FILE_FILE ) {
1264 PR_SetError(PR_IS_DIRECTORY_ERROR, 0);
1265 Debug( LDAP_DEBUG_ANY,
1266 "TLS: error: the key file %s is not a file.\n",
1271 attrs = theTemplate;
1273 if ( ctx->tc_slotname == NULL ) { /* need new slot */
1274 slotID = ++tlsm_slot_count;
1275 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
1277 slot = PK11_FindSlotByName( ctx->tc_slotname );
1280 PRErrorCode errcode = PR_GetError();
1281 Debug( LDAP_DEBUG_ANY,
1282 "TLS: could not find the slot %s for the private key - error %d:%s.\n",
1283 ctx->tc_slotname, errcode,
1284 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1288 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1289 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1290 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1291 rv = PK11_CreateGenericObject( slot, theTemplate, 3, PR_FALSE /* isPerm */ );
1294 PRErrorCode errcode = PR_GetError();
1295 Debug( LDAP_DEBUG_ANY,
1296 "TLS: could not add the certificate %s - error %d:%s.\n",
1297 ctx->tc_certname, errcode,
1298 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1301 /* When adding an encrypted key the PKCS#11 will be set as removed */
1302 /* This will force the token to be seen as re-inserted */
1303 SECMOD_WaitForAnyTokenEvent( pem_module, 0, 0 );
1304 PK11_IsPresent( slot );
1308 PK11_FreeSlot( slot );
1311 tlsm_add_pem_obj( ctx, rv );
1317 tlsm_init_ca_certs( tlsm_ctx *ctx, const char *cacertfile, const char *cacertdir )
1319 PRBool isca = PR_TRUE;
1320 PRStatus status = PR_FAILURE;
1321 PRErrorCode errcode = PR_SUCCESS;
1323 if ( !cacertfile && !cacertdir ) {
1324 /* no checking - not good, but allowed */
1329 int rc = tlsm_add_cert_from_file( ctx, cacertfile, isca, PR_TRUE );
1331 errcode = PR_GetError();
1332 Debug( LDAP_DEBUG_ANY,
1333 "TLS: %s is not a valid CA certificate file - error %d:%s.\n",
1334 cacertfile, errcode,
1335 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1337 Debug( LDAP_DEBUG_TRACE,
1338 "TLS: loaded CA certificate file %s.\n",
1340 status = PR_SUCCESS; /* have at least one good CA - we can proceed */
1348 PRStatus fistatus = PR_FAILURE;
1350 memset( &fi, 0, sizeof(fi) );
1351 fistatus = PR_GetFileInfo( cacertdir, &fi );
1352 if ( PR_SUCCESS != fistatus) {
1353 errcode = PR_GetError();
1354 Debug( LDAP_DEBUG_ANY,
1355 "TLS: could not get info about the CA certificate directory %s - error %d:%s.\n",
1357 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1361 if ( fi.type != PR_FILE_DIRECTORY ) {
1362 Debug( LDAP_DEBUG_ANY,
1363 "TLS: error: the CA certificate directory %s is not a directory.\n",
1368 dir = PR_OpenDir( cacertdir );
1369 if ( NULL == dir ) {
1370 errcode = PR_GetError();
1371 Debug( LDAP_DEBUG_ANY,
1372 "TLS: could not open the CA certificate directory %s - error %d:%s.\n",
1374 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1379 entry = PR_ReadDir( dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN );
1380 if ( ( NULL != entry ) && ( NULL != entry->name ) ) {
1381 char *fullpath = NULL;
1384 ptr = PL_strrstr( entry->name, PEM_CA_HASH_FILE_SUFFIX );
1385 if ( ( ptr == NULL ) || ( *(ptr + PEM_CA_HASH_FILE_SUFFIX_LEN) != '\0' ) ) {
1386 Debug( LDAP_DEBUG_TRACE,
1387 "TLS: file %s does not end in [%s] - does not appear to be a CA certificate "
1388 "directory file with a properly hashed file name - skipping.\n",
1389 entry->name, PEM_CA_HASH_FILE_SUFFIX, 0 );
1392 fullpath = PR_smprintf( "%s/%s", cacertdir, entry->name );
1393 if ( !tlsm_add_cert_from_file( ctx, fullpath, isca, PR_TRUE ) ) {
1394 Debug( LDAP_DEBUG_TRACE,
1395 "TLS: loaded CA certificate file %s from CA certificate directory %s.\n",
1396 fullpath, cacertdir, 0 );
1397 status = PR_SUCCESS; /* found at least 1 valid CA file in the dir */
1399 errcode = PR_GetError();
1400 Debug( LDAP_DEBUG_TRACE,
1401 "TLS: %s is not a valid CA certificate file - error %d:%s.\n",
1403 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1405 PR_smprintf_free( fullpath );
1407 } while ( NULL != entry );
1411 if ( status != PR_SUCCESS ) {
1412 const char *fmtstr = NULL;
1413 if ( cacertfile && cacertdir ) {
1414 fmtstr = "TLS: did not find any valid CA certificates in %s or %s\n";
1416 fmtstr = "TLS: did not find any valid CA certificates in %s%s\n";
1418 Debug( LDAP_DEBUG_ANY, fmtstr, cacertdir ? cacertdir : "",
1419 cacertfile ? cacertfile : "", 0 );
1427 * NSS supports having multiple cert/key databases in the same
1428 * directory, each one having a unique string prefix e.g.
1429 * slapd-01-cert8.db - the prefix here is "slapd-01-"
1430 * this function examines the given certdir - if it looks like
1431 * /path/to/directory/prefix it will return the
1432 * /path/to/directory part in realcertdir, and the prefix in prefix
1435 tlsm_get_certdb_prefix( const char *certdir, char **realcertdir, char **prefix )
1437 char sep = PR_GetDirectorySeparator();
1439 struct PRFileInfo prfi;
1442 *realcertdir = (char *)certdir; /* default is the one passed in */
1444 /* if certdir is not given, just return */
1449 prc = PR_GetFileInfo( certdir, &prfi );
1450 /* if certdir exists (file or directory) then it cannot specify a prefix */
1451 if ( prc == PR_SUCCESS ) {
1455 /* if certdir was given, and there is a '/' in certdir, see if there
1456 is anything after the last '/' - if so, assume it is the prefix */
1457 if ( ( ( ptr = strrchr( certdir, sep ) ) ) && *(ptr+1) ) {
1458 *realcertdir = PL_strndup( certdir, ptr-certdir );
1459 *prefix = PL_strdup( ptr+1 );
1466 * This is the part of the init we defer until we get the
1467 * actual security configuration information. This is
1468 * only called once, protected by a PRCallOnce
1469 * NOTE: This must be done before the first call to SSL_ImportFD,
1470 * especially the setting of the policy
1471 * NOTE: This must be called after fork()
1474 tlsm_deferred_init( void *arg )
1476 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1477 struct ldaptls *lt = ctx->tc_config;
1478 const char *securitydirs[3];
1481 PRErrorCode errcode = 1;
1482 #ifdef HAVE_NSS_INITCONTEXT
1483 NSSInitParameters initParams;
1484 NSSInitContext *initctx = NULL;
1489 #ifdef HAVE_NSS_INITCONTEXT
1490 memset( &initParams, 0, sizeof( initParams ) );
1491 initParams.length = sizeof( initParams );
1492 #endif /* HAVE_NSS_INITCONTEXT */
1494 #ifndef HAVE_NSS_INITCONTEXT
1495 if ( !NSS_IsInitialized() ) {
1496 #endif /* HAVE_NSS_INITCONTEXT */
1498 MOZNSS_DIR will override everything else - you can
1499 always set MOZNSS_DIR to force the use of this
1501 If using MOZNSS, specify the location of the moznss db dir
1502 in the cacertdir directive of the OpenLDAP configuration.
1503 DEFAULT_MOZNSS_DIR will only be used if the code cannot
1504 find a security dir to use based on the current
1508 securitydirs[nn++] = PR_GetEnv( "MOZNSS_DIR" );
1509 securitydirs[nn++] = lt->lt_cacertdir;
1510 securitydirs[nn++] = PR_GetEnv( "DEFAULT_MOZNSS_DIR" );
1511 for ( ii = 0; !done && ( ii < nn ); ++ii ) {
1512 char *realcertdir = NULL;
1513 const char *defprefix = "";
1514 char *prefix = (char *)defprefix;
1515 const char *securitydir = securitydirs[ii];
1516 if ( NULL == securitydir ) {
1520 tlsm_get_certdb_prefix( securitydir, &realcertdir, &prefix );
1521 #ifdef HAVE_NSS_INITCONTEXT
1522 #ifdef INITCONTEXT_HACK
1523 if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
1524 rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
1526 initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
1527 &initParams, NSS_INIT_READONLY );
1528 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1531 initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
1532 &initParams, NSS_INIT_READONLY );
1533 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1536 rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
1539 if ( rc != SECSuccess ) {
1540 errcode = PORT_GetError();
1541 if ( securitydirs[ii] != lt->lt_cacertdir) {
1542 Debug( LDAP_DEBUG_TRACE,
1543 "TLS: could not initialize moznss using security dir %s prefix %s - error %d.\n",
1544 realcertdir, prefix, errcode );
1548 Debug( LDAP_DEBUG_TRACE, "TLS: using moznss security dir %s prefix %s.\n",
1549 realcertdir, prefix, 0 );
1553 if ( realcertdir != securitydir ) {
1554 PL_strfree( realcertdir );
1556 if ( prefix != defprefix ) {
1557 PL_strfree( prefix );
1561 if ( errcode ) { /* no moznss db found, or not using moznss db */
1562 #ifdef HAVE_NSS_INITCONTEXT
1563 int flags = NSS_INIT_READONLY|NSS_INIT_NOCERTDB|NSS_INIT_NOMODDB;
1564 #ifdef INITCONTEXT_HACK
1565 if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
1566 rc = NSS_NoDB_Init( NULL );
1568 initctx = NSS_InitContext( "", "", "", SECMOD_DB,
1569 &initParams, flags );
1570 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1573 initctx = NSS_InitContext( "", "", "", SECMOD_DB,
1574 &initParams, flags );
1575 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1578 rc = NSS_NoDB_Init( NULL );
1580 if ( rc != SECSuccess ) {
1581 errcode = PORT_GetError();
1582 Debug( LDAP_DEBUG_ANY,
1583 "TLS: could not initialize moznss - error %d:%s.\n",
1584 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1588 #ifdef HAVE_NSS_INITCONTEXT
1589 ctx->tc_initctx = initctx;
1592 /* initialize the PEM module */
1593 if ( tlsm_init_pem_module() ) {
1594 errcode = PORT_GetError();
1595 Debug( LDAP_DEBUG_ANY,
1596 "TLS: could not initialize moznss PEM module - error %d:%s.\n",
1597 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1601 if ( tlsm_init_ca_certs( ctx, lt->lt_cacertfile, lt->lt_cacertdir ) ) {
1602 /* if we tried to use lt->lt_cacertdir as an NSS key/cert db, errcode
1603 will be a value other than 1 - print an error message so that the
1604 user will know that failed too */
1605 if ( ( errcode != 1 ) && ( lt->lt_cacertdir ) ) {
1606 char *realcertdir = NULL;
1607 char *prefix = NULL;
1608 tlsm_get_certdb_prefix( lt->lt_cacertdir, &realcertdir, &prefix );
1609 Debug( LDAP_DEBUG_TRACE,
1610 "TLS: could not initialize moznss using security dir %s prefix %s - error %d.\n",
1611 realcertdir, prefix ? prefix : "", errcode );
1612 if ( realcertdir != lt->lt_cacertdir ) {
1613 PL_strfree( realcertdir );
1615 PL_strfree( prefix );
1620 ctx->tc_using_pem = PR_TRUE;
1623 #ifdef HAVE_NSS_INITCONTEXT
1624 if ( !ctx->tc_initctx ) {
1625 ctx->tc_initctx = initctx;
1629 NSS_SetDomesticPolicy();
1631 PK11_SetPasswordFunc( tlsm_pin_prompt );
1633 /* register cleanup function */
1634 /* delete the old one, if any */
1635 NSS_UnregisterShutdown( tlsm_nss_shutdown_cb, NULL );
1636 NSS_RegisterShutdown( tlsm_nss_shutdown_cb, NULL );
1638 #ifndef HAVE_NSS_INITCONTEXT
1640 #endif /* HAVE_NSS_INITCONTEXT */
1646 tlsm_authenticate( tlsm_ctx *ctx, const char *certname, const char *pininfo )
1648 const char *colon = NULL;
1649 char *token_name = NULL;
1650 PK11SlotInfo *slot = NULL;
1653 if ( !certname || !*certname ) {
1657 if ( ( colon = PL_strchr( certname, ':' ) ) ) {
1658 token_name = PL_strndup( certname, colon-certname );
1662 slot = PK11_FindSlotByName( token_name );
1664 slot = PK11_GetInternalKeySlot();
1668 PRErrorCode errcode = PR_GetError();
1669 Debug( LDAP_DEBUG_ANY,
1670 "TLS: could not find the slot for security token %s - error %d:%s.\n",
1671 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1672 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1676 rc = tlsm_authenticate_to_slot( ctx, slot );
1679 PL_strfree( token_name );
1681 PK11_FreeSlot( slot );
1688 * Find and verify the certificate.
1689 * Either fd is given, in which case the cert will be taken from it via SSL_PeerCertificate
1690 * or certname is given, and it will be searched for by name
1693 tlsm_find_and_verify_cert_key(tlsm_ctx *ctx, PRFileDesc *fd, const char *certname, int isServer, CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey)
1695 CERTCertificate *cert = NULL;
1697 void *pin_arg = NULL;
1698 SECKEYPrivateKey *key = NULL;
1700 pin_arg = SSL_RevealPinArg( fd );
1702 cert = PK11_FindCertFromNickname( certname, pin_arg );
1704 PRErrorCode errcode = PR_GetError();
1705 Debug( LDAP_DEBUG_ANY,
1706 "TLS: error: the certificate %s could not be found in the database - error %d:%s\n",
1707 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1711 /* we are verifying the peer cert
1712 we also need to swap the isServer meaning */
1713 cert = SSL_PeerCertificate( fd );
1715 PRErrorCode errcode = PR_GetError();
1716 Debug( LDAP_DEBUG_ANY,
1717 "TLS: error: could not get the certificate from the peer connection - error %d:%s\n",
1718 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), NULL );
1721 isServer = !isServer; /* verify the peer's cert instead */
1724 if ( ctx->tc_slotname ) {
1725 PK11SlotInfo *slot = PK11_FindSlotByName( ctx->tc_slotname );
1726 key = PK11_FindPrivateKeyFromCert( slot, cert, NULL );
1727 PK11_FreeSlot( slot );
1729 key = PK11_FindKeyByAnyCert( cert, pin_arg );
1733 SECCertificateUsage certUsage;
1734 PRBool checkSig = PR_TRUE;
1738 *pRetKey = key; /* caller will deal with this */
1740 SECKEY_DestroyPrivateKey( key );
1743 certUsage = certificateUsageSSLServer;
1745 certUsage = certificateUsageSSLClient;
1747 if ( ctx->tc_verify_cert ) {
1750 checkSig = PR_FALSE;
1752 /* may not have a CA cert - ok - ignore SEC_ERROR_UNKNOWN_ISSUER */
1753 status = tlsm_verify_cert( ctx->tc_certdb, cert, pin_arg,
1754 checkSig, certUsage, SEC_ERROR_UNKNOWN_ISSUER );
1755 if ( status == SECSuccess ) {
1759 PRErrorCode errcode = PR_GetError();
1760 Debug( LDAP_DEBUG_ANY,
1761 "TLS: error: could not find the private key for certificate %s - error %d:%s\n",
1762 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1766 *pRetCert = cert; /* caller will deal with this */
1768 CERT_DestroyCertificate( cert );
1775 tlsm_get_client_auth_data( void *arg, PRFileDesc *fd,
1776 CERTDistNames *caNames, CERTCertificate **pRetCert,
1777 SECKEYPrivateKey **pRetKey )
1779 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1782 /* don't need caNames - this function will call CERT_VerifyCertificateNow
1783 which will verify the cert against the known CAs */
1784 rc = tlsm_find_and_verify_cert_key( ctx, fd, ctx->tc_certname, 0, pRetCert, pRetKey );
1786 Debug( LDAP_DEBUG_ANY,
1787 "TLS: error: unable to perform client certificate authentication for "
1788 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1796 * ctx must have a tc_model that is valid
1797 * certname is in the form [<tokenname>:]<certnickname>
1798 * where <tokenname> is the name of the PKCS11 token
1799 * and <certnickname> is the nickname of the cert/key in
1803 tlsm_clientauth_init( tlsm_ctx *ctx )
1805 SECStatus status = SECFailure;
1808 rc = tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, 0, NULL, NULL );
1810 Debug( LDAP_DEBUG_ANY,
1811 "TLS: error: unable to set up client certificate authentication for "
1812 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1816 status = SSL_GetClientAuthDataHook( ctx->tc_model,
1817 tlsm_get_client_auth_data,
1820 return ( status == SECSuccess ? 0 : -1 );
1824 * Tear down the TLS subsystem. Should only be called once.
1827 tlsm_destroy( void )
1832 tlsm_ctx_new ( struct ldapoptions *lo )
1836 ctx = LDAP_MALLOC( sizeof (*ctx) );
1839 #ifdef LDAP_R_COMPILE
1840 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
1842 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 */
1843 ctx->tc_certdb = NULL;
1844 ctx->tc_certname = NULL;
1845 ctx->tc_pin_file = NULL;
1846 ctx->tc_model = NULL;
1847 memset(&ctx->tc_callonce, 0, sizeof(ctx->tc_callonce));
1848 ctx->tc_require_cert = lo->ldo_tls_require_cert;
1849 ctx->tc_verify_cert = PR_FALSE;
1850 ctx->tc_using_pem = PR_FALSE;
1851 ctx->tc_slotname = NULL;
1852 #ifdef HAVE_NSS_INITCONTEXT
1853 ctx->tc_initctx = NULL;
1854 #endif /* HAVE_NSS_INITCONTEXT */
1855 ctx->tc_pem_objs = NULL;
1856 ctx->tc_n_pem_objs = 0;
1858 return (tls_ctx *)ctx;
1862 tlsm_ctx_ref( tls_ctx *ctx )
1864 tlsm_ctx *c = (tlsm_ctx *)ctx;
1865 #ifdef LDAP_R_COMPILE
1866 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
1869 #ifdef LDAP_R_COMPILE
1870 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
1875 tlsm_ctx_free ( tls_ctx *ctx )
1877 tlsm_ctx *c = (tlsm_ctx *)ctx;
1882 #ifdef LDAP_R_COMPILE
1883 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
1885 refcount = --c->tc_refcnt;
1886 #ifdef LDAP_R_COMPILE
1887 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
1892 PR_Close( c->tc_model );
1893 c->tc_certdb = NULL; /* if not the default, may have to clean up */
1894 PL_strfree( c->tc_certname );
1895 c->tc_certname = NULL;
1896 PL_strfree( c->tc_pin_file );
1897 c->tc_pin_file = NULL;
1898 PL_strfree( c->tc_slotname );
1899 tlsm_free_pem_objs( c );
1900 #ifdef HAVE_NSS_INITCONTEXT
1902 NSS_ShutdownContext( c->tc_initctx );
1903 c->tc_initctx = NULL;
1904 #endif /* HAVE_NSS_INITCONTEXT */
1905 #ifdef LDAP_R_COMPILE
1906 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
1912 * initialize a new TLS context
1915 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
1917 tlsm_ctx *ctx = (tlsm_ctx *)lo->ldo_tls_ctx;
1918 ctx->tc_is_server = is_server;
1924 tlsm_deferred_ctx_init( void *arg )
1926 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1927 PRBool sslv2 = PR_FALSE;
1928 PRBool sslv3 = PR_TRUE;
1929 PRBool tlsv1 = PR_TRUE;
1930 PRBool request_cert = PR_FALSE;
1931 PRInt32 require_cert = PR_FALSE;
1935 if ( tlsm_deferred_init( ctx ) ) {
1936 Debug( LDAP_DEBUG_ANY,
1937 "TLS: could perform TLS system initialization.\n",
1942 ctx->tc_certdb = CERT_GetDefaultCertDB(); /* If there is ever a per-context db, change this */
1944 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
1946 ctx->tc_model = SSL_ImportFD( NULL, fd );
1949 if ( !ctx->tc_model ) {
1950 PRErrorCode err = PR_GetError();
1951 Debug( LDAP_DEBUG_ANY,
1952 "TLS: could perform TLS socket I/O layer initialization - error %d:%s.\n",
1953 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1961 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE ) ) {
1962 Debug( LDAP_DEBUG_ANY,
1963 "TLS: could not set secure mode on.\n",
1968 lt = ctx->tc_config;
1970 /* default is sslv3 and tlsv1 */
1971 if ( lt->lt_protocol_min ) {
1972 if ( lt->lt_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 ) {
1974 } else if ( lt->lt_protocol_min <= LDAP_OPT_X_TLS_PROTOCOL_SSL2 ) {
1976 Debug( LDAP_DEBUG_ANY,
1977 "TLS: warning: minimum TLS protocol level set to "
1978 "include SSLv2 - SSLv2 is insecure - do not use\n", 0, 0, 0 );
1981 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL2, sslv2 ) ) {
1982 Debug( LDAP_DEBUG_ANY,
1983 "TLS: could not set SSLv2 mode on.\n",
1987 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL3, sslv3 ) ) {
1988 Debug( LDAP_DEBUG_ANY,
1989 "TLS: could not set SSLv3 mode on.\n",
1993 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_TLS, tlsv1 ) ) {
1994 Debug( LDAP_DEBUG_ANY,
1995 "TLS: could not set TLSv1 mode on.\n",
2000 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !ctx->tc_is_server ) ) {
2001 Debug( LDAP_DEBUG_ANY,
2002 "TLS: could not set handshake as client.\n",
2006 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, ctx->tc_is_server ) ) {
2007 Debug( LDAP_DEBUG_ANY,
2008 "TLS: could not set handshake as server.\n",
2013 if ( lt->lt_ciphersuite &&
2014 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
2015 Debug( LDAP_DEBUG_ANY,
2016 "TLS: could not set cipher list %s.\n",
2017 lt->lt_ciphersuite, 0, 0 );
2021 if ( ctx->tc_require_cert ) {
2022 request_cert = PR_TRUE;
2023 require_cert = SSL_REQUIRE_NO_ERROR;
2024 if ( ctx->tc_require_cert == LDAP_OPT_X_TLS_DEMAND ||
2025 ctx->tc_require_cert == LDAP_OPT_X_TLS_HARD ) {
2026 require_cert = SSL_REQUIRE_ALWAYS;
2028 if ( ctx->tc_require_cert != LDAP_OPT_X_TLS_ALLOW )
2029 ctx->tc_verify_cert = PR_TRUE;
2031 ctx->tc_verify_cert = PR_FALSE;
2034 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUEST_CERTIFICATE, request_cert ) ) {
2035 Debug( LDAP_DEBUG_ANY,
2036 "TLS: could not set request certificate mode.\n",
2041 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUIRE_CERTIFICATE, require_cert ) ) {
2042 Debug( LDAP_DEBUG_ANY,
2043 "TLS: could not set require certificate mode.\n",
2048 /* set up our cert and key, if any */
2049 if ( lt->lt_certfile ) {
2050 /* if using the PEM module, load the PEM file specified by lt_certfile */
2051 /* otherwise, assume this is the name of a cert already in the db */
2052 if ( ctx->tc_using_pem ) {
2053 /* this sets ctx->tc_certname to the correct value */
2054 int rc = tlsm_add_cert_from_file( ctx, lt->lt_certfile, PR_FALSE, PR_TRUE );
2059 PL_strfree( ctx->tc_certname );
2060 ctx->tc_certname = PL_strdup( lt->lt_certfile );
2064 if ( lt->lt_keyfile ) {
2065 /* if using the PEM module, load the PEM file specified by lt_keyfile */
2066 /* otherwise, assume this is the pininfo for the key */
2067 if ( ctx->tc_using_pem ) {
2068 /* this sets ctx->tc_certname to the correct value */
2069 int rc = tlsm_add_key_from_file( ctx, lt->lt_keyfile );
2074 PL_strfree( ctx->tc_pin_file );
2075 ctx->tc_pin_file = PL_strdup( lt->lt_keyfile );
2079 /* Set up callbacks for use by clients */
2080 if ( !ctx->tc_is_server ) {
2081 if ( SSL_OptionSet( ctx->tc_model, SSL_NO_CACHE, PR_TRUE ) != SECSuccess ) {
2082 PRErrorCode err = PR_GetError();
2083 Debug( LDAP_DEBUG_ANY,
2084 "TLS: error: could not set nocache option for moznss - error %d:%s\n",
2085 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2089 if ( SSL_BadCertHook( ctx->tc_model, tlsm_bad_cert_handler, ctx ) != SECSuccess ) {
2090 PRErrorCode err = PR_GetError();
2091 Debug( LDAP_DEBUG_ANY,
2092 "TLS: error: could not set bad cert handler for moznss - error %d:%s\n",
2093 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2098 since a cert has been specified, assume the client wants to do cert auth
2100 if ( ctx->tc_certname ) {
2101 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
2102 Debug( LDAP_DEBUG_ANY,
2103 "TLS: error: unable to authenticate to the security device for certificate %s\n",
2104 ctx->tc_certname, 0, 0 );
2107 if ( tlsm_clientauth_init( ctx ) ) {
2108 Debug( LDAP_DEBUG_ANY,
2109 "TLS: error: unable to set up client certificate authentication using %s\n",
2110 ctx->tc_certname, 0, 0 );
2114 } else { /* set up secure server */
2116 CERTCertificate *serverCert;
2117 SECKEYPrivateKey *serverKey;
2120 /* must have a certificate for the server to use */
2121 if ( !ctx->tc_certname ) {
2122 Debug( LDAP_DEBUG_ANY,
2123 "TLS: error: no server certificate: must specify a certificate for the server to use\n",
2128 /* authenticate to the server's token - this will do nothing
2129 if the key/cert db is not password protected */
2130 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
2131 Debug( LDAP_DEBUG_ANY,
2132 "TLS: error: unable to authenticate to the security device for certificate %s\n",
2133 ctx->tc_certname, 0, 0 );
2137 /* get the server's key and cert */
2138 if ( tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, ctx->tc_is_server,
2139 &serverCert, &serverKey ) ) {
2140 Debug( LDAP_DEBUG_ANY,
2141 "TLS: error: unable to find and verify server's cert and key for certificate %s\n",
2142 ctx->tc_certname, 0, 0 );
2146 certKEA = NSS_FindCertKEAType( serverCert );
2147 /* configure the socket to be a secure server socket */
2148 status = SSL_ConfigSecureServer( ctx->tc_model, serverCert, serverKey, certKEA );
2149 /* SSL_ConfigSecureServer copies these */
2150 CERT_DestroyCertificate( serverCert );
2151 SECKEY_DestroyPrivateKey( serverKey );
2153 if ( SECSuccess != status ) {
2154 PRErrorCode err = PR_GetError();
2155 Debug( LDAP_DEBUG_ANY,
2156 "TLS: error: unable to configure secure server using certificate %s - error %d:%s\n",
2157 ctx->tc_certname, err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) );
2162 /* Callback for authenticating certificate */
2163 if ( SSL_AuthCertificateHook( ctx->tc_model, tlsm_auth_cert_handler,
2164 ctx->tc_certdb ) != SECSuccess ) {
2165 PRErrorCode err = PR_GetError();
2166 Debug( LDAP_DEBUG_ANY,
2167 "TLS: error: could not set auth cert handler for moznss - error %d:%s\n",
2168 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2172 if ( SSL_HandshakeCallback( ctx->tc_model, tlsm_handshake_complete_cb, ctx ) ) {
2173 PRErrorCode err = PR_GetError();
2174 Debug( LDAP_DEBUG_ANY,
2175 "TLS: error: could not set handshake callback for moznss - error %d:%s\n",
2176 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2184 tlsm_session *session;
2185 Sockbuf_IO_Desc *sbiod;
2186 /* there seems to be no portable way to determine if the
2187 sockbuf sd has been set to nonblocking mode - the
2188 call to ber_pvt_socket_set_nonblock() takes place
2189 before the tls socket is set up, so we cannot
2190 intercept that call either.
2191 On systems where fcntl is available, we can just
2192 F_GETFL and test for O_NONBLOCK. On other systems,
2193 we will just see if the IO op returns EAGAIN or EWOULDBLOCK,
2194 and just set this flag */
2197 * NSS tries hard to be backwards compatible with SSLv2 clients, or
2198 * clients that send an SSLv2 client hello. This message is not
2199 * tagged in any way, so NSS has no way to know if the incoming
2200 * message is a valid SSLv2 client hello or just some bogus data
2201 * (or cleartext LDAP). We store the first byte read from the
2202 * client here. The most common case will be a client sending
2203 * LDAP data instead of SSL encrypted LDAP data. This can happen,
2204 * for example, if using ldapsearch -Z - if the starttls fails,
2205 * the client will fallback to plain cleartext LDAP. So if we
2206 * see that the firstbyte is a valid LDAP tag, we can be
2207 * pretty sure this is happening.
2211 * NSS doesn't return SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, etc.
2212 * when it is blocked, so we have to set a flag in the wrapped send
2213 * and recv calls that tells us what operation NSS was last blocked
2217 #define TLSM_WRITE 2
2221 static struct tls_data *
2222 tlsm_get_pvt_tls_data( PRFileDesc *fd )
2231 myfd = PR_GetIdentitiesLayer( fd, tlsm_layer_id );
2237 p = (struct tls_data *)myfd->secret;
2243 tlsm_is_non_ssl_message( PRFileDesc *fd, ber_tag_t *thebyte )
2248 *thebyte = LBER_DEFAULT;
2251 p = tlsm_get_pvt_tls_data( fd );
2252 if ( p == NULL || p->sbiod == NULL ) {
2256 if ( p->firsttag == LBER_SEQUENCE ) {
2258 *thebyte = p->firsttag;
2266 static tls_session *
2267 tlsm_session_new ( tls_ctx * ctx, int is_server )
2269 tlsm_ctx *c = (tlsm_ctx *)ctx;
2270 tlsm_session *session;
2275 c->tc_is_server = is_server;
2276 status = PR_CallOnceWithArg( &c->tc_callonce, tlsm_deferred_ctx_init, c );
2277 if ( PR_SUCCESS != status ) {
2278 PRErrorCode err = PR_GetError();
2279 Debug( LDAP_DEBUG_ANY,
2280 "TLS: error: could not initialize moznss security context - error %d:%s\n",
2281 err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT), NULL );
2285 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
2290 session = SSL_ImportFD( c->tc_model, fd );
2297 /* 0 means use the defaults here */
2298 SSL_ConfigServerSessionIDCache( 0, 0, 0, NULL );
2301 rc = SSL_ResetHandshake( session, is_server );
2303 PRErrorCode err = PR_GetError();
2304 Debug( LDAP_DEBUG_TRACE,
2305 "TLS: error: new session - reset handshake failure %d - error %d:%s\n",
2307 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
2309 PR_Close( session );
2313 return (tls_session *)session;
2317 tlsm_session_accept_or_connect( tls_session *session, int is_accept )
2319 tlsm_session *s = (tlsm_session *)session;
2320 int rc = SSL_ForceHandshake( s );
2321 const char *op = is_accept ? "accept" : "connect";
2324 PRErrorCode err = PR_GetError();
2326 if ( err == PR_WOULD_BLOCK_ERROR ) {
2327 ber_tag_t thetag = LBER_DEFAULT;
2328 /* see if we are blocked because of a bogus packet */
2329 if ( tlsm_is_non_ssl_message( s, &thetag ) ) { /* see if we received a non-SSL message */
2330 Debug( LDAP_DEBUG_ANY,
2331 "TLS: error: %s - error - received non-SSL message [0x%x]\n",
2332 op, (unsigned int)thetag, 0 );
2333 /* reset error to something more descriptive */
2334 PR_SetError( SSL_ERROR_RX_MALFORMED_HELLO_REQUEST, EPROTO );
2337 Debug( LDAP_DEBUG_ANY,
2338 "TLS: error: %s - force handshake failure: errno %d - moznss error %d\n",
2346 tlsm_session_accept( tls_session *session )
2348 return tlsm_session_accept_or_connect( session, 1 );
2352 tlsm_session_connect( LDAP *ld, tls_session *session )
2354 return tlsm_session_accept_or_connect( session, 0 );
2358 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
2360 int prerror = PR_GetError();
2362 if ( ( prerror == PR_PENDING_INTERRUPT_ERROR ) || ( prerror == PR_WOULD_BLOCK_ERROR ) ) {
2363 tlsm_session *s = (tlsm_session *)session;
2364 struct tls_data *p = tlsm_get_pvt_tls_data( s );
2366 if ( p && ( p->io_flag == TLSM_READ ) ) {
2367 sb->sb_trans_needs_read = 1;
2369 } else if ( p && ( p->io_flag == TLSM_WRITE ) ) {
2370 sb->sb_trans_needs_write = 1;
2379 tlsm_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
2382 int prerror = PR_GetError();
2384 i = PR_GetErrorTextLength();
2386 char *msg = LDAP_MALLOC( i+1 );
2387 PR_GetErrorText( msg );
2388 memcpy( buf, msg, len );
2391 PR_GetErrorText( buf );
2392 } else if ( prerror ) {
2393 i = PR_snprintf( buf, len, "TLS error %d:%s",
2394 prerror, PR_ErrorToString( prerror, PR_LANGUAGE_I_DEFAULT ) );
2397 return ( i > 0 ) ? buf : NULL;
2401 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
2403 tlsm_session *s = (tlsm_session *)session;
2404 CERTCertificate *cert;
2406 cert = SSL_LocalCertificate( s );
2407 if (!cert) return LDAP_INVALID_CREDENTIALS;
2409 der_dn->bv_val = (char *)cert->derSubject.data;
2410 der_dn->bv_len = cert->derSubject.len;
2411 CERT_DestroyCertificate( cert );
2416 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
2418 tlsm_session *s = (tlsm_session *)session;
2419 CERTCertificate *cert;
2421 cert = SSL_PeerCertificate( s );
2422 if (!cert) return LDAP_INVALID_CREDENTIALS;
2424 der_dn->bv_val = (char *)cert->derSubject.data;
2425 der_dn->bv_len = cert->derSubject.len;
2426 CERT_DestroyCertificate( cert );
2430 /* what kind of hostname were we given? */
2436 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
2438 tlsm_session *s = (tlsm_session *)session;
2439 CERTCertificate *cert;
2440 const char *name, *domain = NULL, *ptr;
2441 int ret, ntype = IS_DNS, nlen, dlen;
2442 #ifdef LDAP_PF_INET6
2443 struct in6_addr addr;
2445 struct in_addr addr;
2450 if( ldap_int_hostname &&
2451 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
2453 name = ldap_int_hostname;
2457 nlen = strlen( name );
2459 cert = SSL_PeerCertificate( s );
2461 Debug( LDAP_DEBUG_ANY,
2462 "TLS: unable to get peer certificate.\n",
2464 /* if this was a fatal condition, things would have
2465 * aborted long before now.
2467 return LDAP_SUCCESS;
2470 #ifdef LDAP_PF_INET6
2471 if (name[0] == '[' && strchr(name, ']')) {
2472 char *n2 = ldap_strdup(name+1);
2473 *strchr(n2, ']') = 0;
2474 if (inet_pton(AF_INET6, n2, &addr))
2479 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
2480 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
2482 if (ntype == IS_DNS ) {
2483 domain = strchr( name, '.' );
2485 dlen = nlen - ( domain - name );
2488 ret = LDAP_LOCAL_ERROR;
2490 rv = CERT_FindCertExtension( cert, SEC_OID_X509_SUBJECT_ALT_NAME,
2492 if ( rv == SECSuccess && altname.data ) {
2494 CERTGeneralName *names, *cur;
2496 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
2498 ret = LDAP_NO_MEMORY;
2502 names = cur = CERT_DecodeAltNameExtension(arena, &altname);
2511 if ( !cur->name.other.len ) continue;
2513 host = (char *)cur->name.other.data;
2514 hlen = cur->name.other.len;
2516 if ( cur->type == certDNSName ) {
2517 if ( ntype != IS_DNS ) continue;
2519 /* is this an exact match? */
2520 if ( nlen == hlen && !strncasecmp( name, host, nlen )) {
2525 /* is this a wildcard match? */
2526 if ( domain && host[0] == '*' && host[1] == '.' &&
2527 dlen == hlen-1 && !strncasecmp( domain, host+1, dlen )) {
2531 } else if ( cur->type == certIPAddress ) {
2532 if ( ntype == IS_DNS ) continue;
2534 #ifdef LDAP_PF_INET6
2535 if (ntype == IS_IP6 && hlen != sizeof(struct in6_addr)) {
2539 if (ntype == IS_IP4 && hlen != sizeof(struct in_addr)) {
2542 if (!memcmp(host, &addr, hlen)) {
2547 } while (( cur = CERT_GetNextGeneralName( cur )) != names );
2549 PORT_FreeArena( arena, PR_FALSE );
2550 SECITEM_FreeItem( &altname, PR_FALSE );
2552 /* no altnames matched, try the CN */
2553 if ( ret != LDAP_SUCCESS ) {
2554 /* find the last CN */
2555 CERTRDN *rdn, **rdns;
2556 CERTAVA *lastava = NULL;
2560 rdns = cert->subject.rdns;
2561 while ( rdns && ( rdn = *rdns++ )) {
2562 CERTAVA *ava, **avas = rdn->avas;
2563 while ( avas && ( ava = *avas++ )) {
2564 if ( CERT_GetAVATag( ava ) == SEC_OID_AVA_COMMON_NAME )
2569 SECItem *av = CERT_DecodeAVAValue( &lastava->value );
2571 if ( av->len == nlen && !strncasecmp( name, (char *)av->data, nlen )) {
2573 } else if ( av->data[0] == '*' && av->data[1] == '.' &&
2574 domain && dlen == av->len - 1 && !strncasecmp( name,
2575 (char *)(av->data+1), dlen )) {
2579 if ( len >= sizeof(buf) )
2580 len = sizeof(buf)-1;
2581 memcpy( buf, av->data, len );
2584 SECITEM_FreeItem( av, PR_TRUE );
2587 if ( ret != LDAP_SUCCESS ) {
2588 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
2589 "common name in certificate (%s).\n",
2591 ret = LDAP_CONNECT_ERROR;
2592 if ( ld->ld_error ) {
2593 LDAP_FREE( ld->ld_error );
2595 ld->ld_error = LDAP_STRDUP(
2596 _("TLS: hostname does not match CN in peer certificate"));
2601 CERT_DestroyCertificate( cert );
2606 tlsm_session_strength( tls_session *session )
2608 tlsm_session *s = (tlsm_session *)session;
2611 rc = SSL_SecurityStatus( s, NULL, NULL, NULL, &keySize,
2613 return rc ? 0 : keySize;
2617 * TLS support for LBER Sockbufs
2620 static PRStatus PR_CALLBACK
2621 tlsm_PR_Close(PRFileDesc *fd)
2623 int rc = PR_SUCCESS;
2625 /* we don't need to actually close anything here, just
2626 pop our io layer off the stack */
2627 fd->secret = NULL; /* must have been freed before calling PR_Close */
2629 fd = PR_PopIOLayer( fd, tlsm_layer_id );
2630 /* if we are not the last layer, pass the close along */
2635 rc = fd->methods->close( fd );
2638 /* we are the last layer - just call our dtor */
2645 static PRStatus PR_CALLBACK
2646 tlsm_PR_Shutdown(PRFileDesc *fd, PRShutdownHow how)
2648 int rc = PR_SUCCESS;
2651 rc = PR_Shutdown( fd->lower, how );
2657 static int PR_CALLBACK
2658 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
2659 PRIntervalTime timeout)
2664 if ( buf == NULL || len <= 0 ) return 0;
2666 p = tlsm_get_pvt_tls_data( fd );
2668 if ( p == NULL || p->sbiod == NULL ) {
2672 rc = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
2674 tlsm_map_error( errno );
2675 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2676 p->nonblock = PR_TRUE; /* fd is using non-blocking io */
2677 } else if ( errno ) { /* real error */
2678 Debug( LDAP_DEBUG_TRACE,
2679 "TLS: error: tlsm_PR_Recv returned %d - error %d:%s\n",
2680 rc, errno, STRERROR(errno) );
2682 } else if ( ( rc > 0 ) && ( len > 0 ) && ( p->firsttag == LBER_DEFAULT ) ) {
2683 p->firsttag = (ber_tag_t)*((char *)buf);
2685 p->io_flag = TLSM_READ;
2690 static int PR_CALLBACK
2691 tlsm_PR_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
2692 PRIntervalTime timeout)
2697 if ( buf == NULL || len <= 0 ) return 0;
2699 p = tlsm_get_pvt_tls_data( fd );
2701 if ( p == NULL || p->sbiod == NULL ) {
2705 rc = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
2707 tlsm_map_error( errno );
2708 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2709 p->nonblock = PR_TRUE;
2710 } else if ( errno ) { /* real error */
2711 Debug( LDAP_DEBUG_TRACE,
2712 "TLS: error: tlsm_PR_Send returned %d - error %d:%s\n",
2713 rc, errno, STRERROR(errno) );
2716 p->io_flag = TLSM_WRITE;
2721 static int PR_CALLBACK
2722 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
2724 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2727 static int PR_CALLBACK
2728 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
2730 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2733 static PRStatus PR_CALLBACK
2734 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
2739 p = tlsm_get_pvt_tls_data( fd );
2741 if ( p == NULL || p->sbiod == NULL ) {
2744 len = sizeof(PRNetAddr);
2745 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
2748 static PRStatus PR_CALLBACK
2749 tlsm_PR_GetSocketOption(PRFileDesc *fd, PRSocketOptionData *data)
2752 p = tlsm_get_pvt_tls_data( fd );
2758 /* only the nonblocking option is supported at this time
2759 MozNSS SSL code needs it */
2760 if ( data->option != PR_SockOpt_Nonblocking ) {
2761 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2765 int flags = fcntl( p->sbiod->sbiod_sb->sb_fd, F_GETFL );
2766 data->value.non_blocking = (flags & O_NONBLOCK) ? PR_TRUE : PR_FALSE;
2768 data->value.non_blocking = p->nonblock;
2773 static PRStatus PR_CALLBACK
2776 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2780 static PRFileDesc * PR_CALLBACK
2783 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2787 static PRInt16 PR_CALLBACK
2790 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2794 static PRInt32 PR_CALLBACK
2797 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2801 static PRInt64 PR_CALLBACK
2806 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2811 static const PRIOMethods tlsm_PR_methods = {
2813 tlsm_PR_Close, /* close */
2814 tlsm_PR_Read, /* read */
2815 tlsm_PR_Write, /* write */
2816 tlsm_PR_i32_unimp, /* available */
2817 tlsm_PR_i64_unimp, /* available64 */
2818 tlsm_PR_prs_unimp, /* fsync */
2819 tlsm_PR_i32_unimp, /* seek */
2820 tlsm_PR_i64_unimp, /* seek64 */
2821 tlsm_PR_prs_unimp, /* fileInfo */
2822 tlsm_PR_prs_unimp, /* fileInfo64 */
2823 tlsm_PR_i32_unimp, /* writev */
2824 tlsm_PR_prs_unimp, /* connect */
2825 tlsm_PR_pfd_unimp, /* accept */
2826 tlsm_PR_prs_unimp, /* bind */
2827 tlsm_PR_prs_unimp, /* listen */
2828 (PRShutdownFN)tlsm_PR_Shutdown, /* shutdown */
2829 tlsm_PR_Recv, /* recv */
2830 tlsm_PR_Send, /* send */
2831 tlsm_PR_i32_unimp, /* recvfrom */
2832 tlsm_PR_i32_unimp, /* sendto */
2833 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
2834 tlsm_PR_i32_unimp, /* acceptread */
2835 tlsm_PR_i32_unimp, /* transmitfile */
2836 tlsm_PR_prs_unimp, /* getsockname */
2837 tlsm_PR_GetPeerName, /* getpeername */
2838 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
2839 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
2840 tlsm_PR_GetSocketOption, /* getsocketoption */
2841 tlsm_PR_i32_unimp, /* setsocketoption */
2842 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
2843 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
2844 tlsm_PR_i32_unimp, /* reserved for future use */
2845 tlsm_PR_i32_unimp, /* reserved for future use */
2846 tlsm_PR_i32_unimp, /* reserved for future use */
2847 tlsm_PR_i32_unimp /* reserved for future use */
2851 * Initialize TLS subsystem. Should be called only once.
2852 * See tlsm_deferred_init for the bulk of the init process
2859 tlsm_layer_id = PR_GetUniqueIdentity( "OpenLDAP" );
2865 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
2868 tlsm_session *session = arg;
2871 assert( sbiod != NULL );
2873 p = LBER_MALLOC( sizeof( *p ) );
2878 fd = PR_GetIdentitiesLayer( session, tlsm_layer_id );
2884 fd->secret = (PRFilePrivate *)p;
2885 p->session = session;
2887 p->firsttag = LBER_DEFAULT;
2888 sbiod->sbiod_pvt = p;
2893 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
2897 assert( sbiod != NULL );
2898 assert( sbiod->sbiod_pvt != NULL );
2900 p = (struct tls_data *)sbiod->sbiod_pvt;
2901 PR_Close( p->session );
2902 LBER_FREE( sbiod->sbiod_pvt );
2903 sbiod->sbiod_pvt = NULL;
2908 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
2912 assert( sbiod != NULL );
2913 assert( sbiod->sbiod_pvt != NULL );
2915 p = (struct tls_data *)sbiod->sbiod_pvt;
2916 PR_Shutdown( p->session, PR_SHUTDOWN_BOTH );
2921 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
2925 assert( sbiod != NULL );
2926 assert( sbiod->sbiod_pvt != NULL );
2928 p = (struct tls_data *)sbiod->sbiod_pvt;
2930 if ( opt == LBER_SB_OPT_GET_SSL ) {
2931 *((tlsm_session **)arg) = p->session;
2934 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
2935 if ( p && ( SSL_DataPending( p->session ) > 0 ) ) {
2941 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
2945 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2951 assert( sbiod != NULL );
2952 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2954 p = (struct tls_data *)sbiod->sbiod_pvt;
2956 ret = PR_Recv( p->session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2958 err = PR_GetError();
2959 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2960 sbiod->sbiod_sb->sb_trans_needs_read = 1;
2961 sock_errset(EWOULDBLOCK);
2964 sbiod->sbiod_sb->sb_trans_needs_read = 0;
2970 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2976 assert( sbiod != NULL );
2977 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2979 p = (struct tls_data *)sbiod->sbiod_pvt;
2981 ret = PR_Send( p->session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2983 err = PR_GetError();
2984 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2985 sbiod->sbiod_sb->sb_trans_needs_write = 1;
2986 sock_errset(EWOULDBLOCK);
2990 sbiod->sbiod_sb->sb_trans_needs_write = 0;
2995 static Sockbuf_IO tlsm_sbio =
2997 tlsm_sb_setup, /* sbi_setup */
2998 tlsm_sb_remove, /* sbi_remove */
2999 tlsm_sb_ctrl, /* sbi_ctrl */
3000 tlsm_sb_read, /* sbi_read */
3001 tlsm_sb_write, /* sbi_write */
3002 tlsm_sb_close /* sbi_close */
3005 tls_impl ldap_int_tls_impl = {
3017 tlsm_session_connect,
3018 tlsm_session_accept,
3019 tlsm_session_upflags,
3020 tlsm_session_errmsg,
3022 tlsm_session_peer_dn,
3023 tlsm_session_chkhost,
3024 tlsm_session_strength,
3028 #ifdef LDAP_R_COMPILE
3037 #endif /* HAVE_MOZNSS */