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 /* NSS 3.12.5 and later have NSS_InitContext */
65 #if NSS_VMAJOR <= 3 && NSS_VMINOR <= 12 && NSS_VPATCH < 5
68 #define HAVE_NSS_INITCONTEXT 1
71 /* InitContext does not currently work in server mode */
72 /* #define INITCONTEXT_HACK 1 */
74 typedef struct tlsm_ctx {
77 PRBool tc_verify_cert;
78 CERTCertDBHandle *tc_certdb;
81 struct ldaptls *tc_config;
84 PRCallOnceType tc_callonce;
86 char *tc_slotname; /* if using pem */
87 #ifdef HAVE_NSS_INITCONTEXT
88 NSSInitContext *tc_initctx; /* the NSS context */
90 PK11GenericObject **tc_pem_objs; /* array of objects to free */
91 int tc_n_pem_objs; /* number of objects */
93 ldap_pvt_thread_mutex_t tc_refmutex;
97 typedef PRFileDesc tlsm_session;
99 static PRDescIdentity tlsm_layer_id;
101 static const PRIOMethods tlsm_PR_methods;
103 #define PEM_LIBRARY "nsspem"
104 #define PEM_MODULE "PEM"
105 /* hash files for use with cacertdir have this file name suffix */
106 #define PEM_CA_HASH_FILE_SUFFIX ".0"
107 #define PEM_CA_HASH_FILE_SUFFIX_LEN 2
109 static SECMODModule *pem_module;
111 #define DEFAULT_TOKEN_NAME "default"
112 /* sprintf format used to create token name */
113 #define TLSM_PEM_TOKEN_FMT "PEM Token #%ld"
115 static int tlsm_slot_count;
117 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
118 (x)->pValue=(v); (x)->ulValueLen = (l);
120 /* forward declaration */
121 static int tlsm_init( void );
123 #ifdef LDAP_R_COMPILE
126 tlsm_thr_init( void )
130 #endif /* LDAP_R_COMPILE */
133 tlsm_dump_cipher_info(PRFileDesc *fd)
137 for (ii = 0; ii < SSL_NumImplementedCiphers; ++ii) {
138 PRInt32 cipher = (PRInt32)SSL_ImplementedCiphers[ii];
139 PRBool enabled = PR_FALSE;
141 SSLCipherSuiteInfo info;
144 SSL_CipherPrefGet(fd, cipher, &enabled);
146 SSL_CipherPrefGetDefault(cipher, &enabled);
148 SSL_CipherPolicyGet(cipher, &policy);
149 SSL_GetCipherSuiteInfo(cipher, &info, (PRUintn)sizeof(info));
150 Debug( LDAP_DEBUG_TRACE,
151 "TLS: cipher: %d - %s, enabled: %d, ",
152 info.cipherSuite, info.cipherSuiteName, enabled );
153 Debug( LDAP_DEBUG_TRACE,
154 "policy: %d\n", policy, 0, 0 );
160 /* Cipher definitions */
162 char *ossl_name; /* The OpenSSL cipher name */
163 int num; /* The cipher id */
164 int attr; /* cipher attributes: algorithms, etc */
165 int version; /* protocol version valid for this cipher */
166 int bits; /* bits of strength */
167 int alg_bits; /* bits of the algorithm */
168 int strength; /* LOW, MEDIUM, HIGH */
169 int enabled; /* Enabled by default? */
172 /* cipher attributes */
173 #define SSL_kRSA 0x00000001L
174 #define SSL_aRSA 0x00000002L
175 #define SSL_aDSS 0x00000004L
176 #define SSL_DSS SSL_aDSS
177 #define SSL_eNULL 0x00000008L
178 #define SSL_DES 0x00000010L
179 #define SSL_3DES 0x00000020L
180 #define SSL_RC4 0x00000040L
181 #define SSL_RC2 0x00000080L
182 #define SSL_AES 0x00000100L
183 #define SSL_MD5 0x00000200L
184 #define SSL_SHA1 0x00000400L
185 #define SSL_SHA SSL_SHA1
186 #define SSL_RSA (SSL_kRSA|SSL_aRSA)
188 /* cipher strength */
189 #define SSL_NULL 0x00000001L
190 #define SSL_EXPORT40 0x00000002L
191 #define SSL_EXPORT56 0x00000004L
192 #define SSL_LOW 0x00000008L
193 #define SSL_MEDIUM 0x00000010L
194 #define SSL_HIGH 0x00000020L
196 #define SSL2 0x00000001L
197 #define SSL3 0x00000002L
198 /* OpenSSL treats SSL3 and TLSv1 the same */
201 /* Cipher translation */
202 static cipher_properties ciphers_def[] = {
204 {"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},
205 {"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},
206 {"RC4-MD5", SSL_EN_RC4_128_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
207 {"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},
208 {"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},
209 {"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},
212 {"RC4-MD5", SSL_RSA_WITH_RC4_128_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
213 {"RC4-SHA", SSL_RSA_WITH_RC4_128_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA1, SSL3, 128, 128, SSL_MEDIUM, SSL_NOT_ALLOWED},
214 {"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},
215 {"DES-CBC-SHA", SSL_RSA_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA1, SSL3, 56, 56, SSL_LOW, SSL_ALLOWED},
216 {"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},
217 {"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},
218 {"NULL-MD5", SSL_RSA_WITH_NULL_MD5, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_MD5, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
219 {"NULL-SHA", SSL_RSA_WITH_NULL_SHA, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_SHA1, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
222 {"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},
223 {"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},
224 {"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},
225 {"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},
228 #define ciphernum (sizeof(ciphers_def)/sizeof(cipher_properties))
230 /* given err which is the current errno, calls PR_SetError with
231 the corresponding NSPR error code */
233 tlsm_map_error(int err)
239 prError = PR_NO_ACCESS_RIGHTS_ERROR;
242 prError = PR_ADDRESS_IN_USE_ERROR;
245 prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
248 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
251 prError = PR_WOULD_BLOCK_ERROR;
254 * On QNX and Neutrino, EALREADY is defined as EBUSY.
256 #if EALREADY != EBUSY
258 prError = PR_ALREADY_INITIATED_ERROR;
262 prError = PR_BAD_DESCRIPTOR_ERROR;
266 prError = PR_IO_ERROR;
270 prError = PR_FILESYSTEM_MOUNTED_ERROR;
273 prError = PR_CONNECT_ABORTED_ERROR;
276 prError = PR_CONNECT_REFUSED_ERROR;
279 prError = PR_CONNECT_RESET_ERROR;
282 prError = PR_DEADLOCK_ERROR;
286 prError = PR_DIRECTORY_CORRUPTED_ERROR;
291 prError = PR_NO_DEVICE_SPACE_ERROR;
295 prError = PR_FILE_EXISTS_ERROR;
298 prError = PR_ACCESS_FAULT_ERROR;
301 prError = PR_FILE_TOO_BIG_ERROR;
304 prError = PR_HOST_UNREACHABLE_ERROR;
307 prError = PR_IN_PROGRESS_ERROR;
310 prError = PR_PENDING_INTERRUPT_ERROR;
313 prError = PR_INVALID_ARGUMENT_ERROR;
316 prError = PR_IO_ERROR;
319 prError = PR_IS_CONNECTED_ERROR;
322 prError = PR_IS_DIRECTORY_ERROR;
325 prError = PR_LOOP_ERROR;
328 prError = PR_PROC_DESC_TABLE_FULL_ERROR;
331 prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
334 prError = PR_INVALID_ARGUMENT_ERROR;
338 prError = PR_REMOTE_FILE_ERROR;
342 prError = PR_NAME_TOO_LONG_ERROR;
345 prError = PR_NETWORK_UNREACHABLE_ERROR;
348 prError = PR_SYS_DESC_TABLE_FULL_ERROR;
351 * On SCO OpenServer 5, ENOBUFS is defined as ENOSR.
353 #if defined(ENOBUFS) && (ENOBUFS != ENOSR)
355 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
359 prError = PR_FILE_NOT_FOUND_ERROR;
362 prError = PR_FILE_NOT_FOUND_ERROR;
365 prError = PR_FILE_IS_LOCKED_ERROR;
369 prError = PR_REMOTE_FILE_ERROR;
373 prError = PR_OUT_OF_MEMORY_ERROR;
376 prError = PR_INVALID_ARGUMENT_ERROR;
379 prError = PR_NO_DEVICE_SPACE_ERROR;
383 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
387 prError = PR_NOT_CONNECTED_ERROR;
390 prError = PR_NOT_DIRECTORY_ERROR;
393 prError = PR_NOT_SOCKET_ERROR;
396 prError = PR_FILE_NOT_FOUND_ERROR;
399 prError = PR_NOT_TCP_SOCKET_ERROR;
403 prError = PR_BUFFER_OVERFLOW_ERROR;
407 prError = PR_NO_ACCESS_RIGHTS_ERROR;
410 prError = PR_CONNECT_RESET_ERROR;
414 prError = PR_IO_ERROR;
417 case EPROTONOSUPPORT:
418 prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
421 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
424 prError = PR_INVALID_METHOD_ERROR;
427 prError = PR_READ_ONLY_FILESYSTEM_ERROR;
430 prError = PR_INVALID_METHOD_ERROR;
433 prError = PR_IO_TIMEOUT_ERROR;
435 #if EWOULDBLOCK != EAGAIN
437 prError = PR_WOULD_BLOCK_ERROR;
441 prError = PR_NOT_SAME_DEVICE_ERROR;
444 prError = PR_UNKNOWN_ERROR;
447 PR_SetError( prError, err );
451 * cipher_list is an integer array with the following values:
452 * -1: never enable this cipher
457 nss_parse_ciphers(const char *cipherstr, int cipher_list[ciphernum])
466 /* All disabled to start */
467 for (i=0; i<ciphernum; i++)
470 ciphertip = strdup(cipherstr);
471 cipher = ciphers = ciphertip;
473 while (ciphers && (strlen(ciphers))) {
474 while ((*cipher) && (isspace(*cipher)))
479 case '+': /* Add something */
483 case '-': /* Subtract something */
487 case '!': /* Disable something */
496 if ((ciphers = strchr(cipher, ':'))) {
500 /* Do the easy one first */
501 if (!strcmp(cipher, "ALL")) {
502 for (i=0; i<ciphernum; i++) {
503 if (!(ciphers_def[i].attr & SSL_eNULL))
504 cipher_list[i] = action;
506 } else if (!strcmp(cipher, "COMPLEMENTOFALL")) {
507 for (i=0; i<ciphernum; i++) {
508 if ((ciphers_def[i].attr & SSL_eNULL))
509 cipher_list[i] = action;
511 } else if (!strcmp(cipher, "DEFAULT")) {
512 for (i=0; i<ciphernum; i++) {
513 cipher_list[i] = ciphers_def[i].enabled == SSL_ALLOWED ? 1 : 0;
522 while (c && (strlen(c))) {
524 if ((c = strchr(cipher, '+'))) {
528 if (!strcmp(cipher, "RSA")) {
530 } else if ((!strcmp(cipher, "NULL")) || (!strcmp(cipher, "eNULL"))) {
532 } else if (!strcmp(cipher, "AES")) {
534 } else if (!strcmp(cipher, "3DES")) {
536 } else if (!strcmp(cipher, "DES")) {
538 } else if (!strcmp(cipher, "RC4")) {
540 } else if (!strcmp(cipher, "RC2")) {
542 } else if (!strcmp(cipher, "MD5")) {
544 } else if ((!strcmp(cipher, "SHA")) || (!strcmp(cipher, "SHA1"))) {
546 } else if (!strcmp(cipher, "SSLv2")) {
548 } else if (!strcmp(cipher, "SSLv3")) {
550 } else if (!strcmp(cipher, "TLSv1")) {
552 } else if (!strcmp(cipher, "HIGH")) {
553 strength |= SSL_HIGH;
554 } else if (!strcmp(cipher, "MEDIUM")) {
555 strength |= SSL_MEDIUM;
556 } else if (!strcmp(cipher, "LOW")) {
558 } else if ((!strcmp(cipher, "EXPORT")) || (!strcmp(cipher, "EXP"))) {
559 strength |= SSL_EXPORT40|SSL_EXPORT56;
560 } else if (!strcmp(cipher, "EXPORT40")) {
561 strength |= SSL_EXPORT40;
562 } else if (!strcmp(cipher, "EXPORT56")) {
563 strength |= SSL_EXPORT56;
571 /* If we have a mask, apply it. If not then perhaps they provided
572 * a specific cipher to enable.
574 if (mask || strength || protocol) {
575 for (i=0; i<ciphernum; i++) {
576 if (((ciphers_def[i].attr & mask) ||
577 (ciphers_def[i].strength & strength) ||
578 (ciphers_def[i].version & protocol)) &&
579 (cipher_list[i] != -1)) {
580 /* Enable the NULL ciphers only if explicity
582 if (ciphers_def[i].attr & SSL_eNULL) {
583 if (mask & SSL_eNULL)
584 cipher_list[i] = action;
586 cipher_list[i] = action;
590 for (i=0; i<ciphernum; i++) {
591 if (!strcmp(ciphers_def[i].ossl_name, cipher) &&
592 cipher_list[1] != -1)
593 cipher_list[i] = action;
602 /* See if any ciphers were enabled */
604 for (i=0; i<ciphernum; i++) {
605 if (cipher_list[i] == 1)
615 tlsm_parse_ciphers(tlsm_ctx *ctx, const char *str)
617 int cipher_state[ciphernum];
623 rv = nss_parse_ciphers(str, cipher_state);
626 /* First disable everything */
627 for (i = 0; i < SSL_NumImplementedCiphers; i++)
628 SSL_CipherPrefSet(ctx->tc_model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
630 /* Now enable what was requested */
631 for (i=0; i<ciphernum; i++) {
632 SSLCipherSuiteInfo suite;
635 if (SSL_GetCipherSuiteInfo(ciphers_def[i].num, &suite, sizeof suite)
637 enabled = cipher_state[i] < 0 ? 0 : cipher_state[i];
638 if (enabled == SSL_ALLOWED) {
639 if (PK11_IsFIPS() && !suite.isFIPS)
640 enabled = SSL_NOT_ALLOWED;
642 SSL_CipherPrefSet(ctx->tc_model, ciphers_def[i].num, enabled);
647 return rv == 1 ? 0 : -1;
651 tlsm_bad_cert_handler(void *arg, PRFileDesc *ssl)
653 SECStatus success = SECSuccess;
655 tlsm_ctx *ctx = (tlsm_ctx *)arg;
661 err = PORT_GetError();
664 case SEC_ERROR_UNTRUSTED_ISSUER:
665 case SEC_ERROR_UNKNOWN_ISSUER:
666 case SEC_ERROR_EXPIRED_CERTIFICATE:
667 if (ctx->tc_verify_cert) {
668 success = SECFailure;
671 /* we bypass NSS's hostname checks and do our own */
672 case SSL_ERROR_BAD_CERT_DOMAIN:
675 success = SECFailure;
683 tlsm_dump_security_status(PRFileDesc *fd)
685 char * cp; /* bulk cipher name */
686 char * ip; /* cert issuer DN */
687 char * sp; /* cert subject DN */
688 int op; /* High, Low, Off */
689 int kp0; /* total key bits */
690 int kp1; /* secret key bits */
691 SSL3Statistics * ssl3stats = SSL_GetStatistics();
693 SSL_SecurityStatus( fd, &op, &cp, &kp0, &kp1, &ip, &sp );
694 Debug( LDAP_DEBUG_TRACE,
695 "TLS certificate verification: subject: %s, issuer: %s, cipher: %s, ",
696 sp ? sp : "-unknown-", ip ? ip : "-unknown-", cp ? cp : "-unknown-" );
700 Debug( LDAP_DEBUG_TRACE,
701 "security level: %s, secret key bits: %d, total key bits: %d, ",
702 ((op == SSL_SECURITY_STATUS_ON_HIGH) ? "high" :
703 ((op == SSL_SECURITY_STATUS_ON_LOW) ? "low" : "off")),
706 Debug( LDAP_DEBUG_TRACE,
707 "cache hits: %ld, cache misses: %ld, cache not reusable: %ld\n",
708 ssl3stats->hch_sid_cache_hits, ssl3stats->hch_sid_cache_misses,
709 ssl3stats->hch_sid_cache_not_ok );
715 tlsm_handshake_complete_cb( PRFileDesc *fd, void *client_data )
717 tlsm_dump_security_status( fd );
720 #ifdef READ_PASSWORD_FROM_FILE
722 tlsm_get_pin_from_file(const char *token_name, tlsm_ctx *ctx)
725 char *contents = NULL;
728 char *candidate = NULL;
729 PRFileInfo file_info;
730 PRFileDesc *pwd_fileptr = PR_Open( ctx->tc_pin_file, PR_RDONLY, 00400 );
732 /* open the password file */
733 if ( !pwd_fileptr ) {
734 PRErrorCode errcode = PR_GetError();
735 Debug( LDAP_DEBUG_ANY,
736 "TLS: could not open security pin file %s - error %d:%s.\n",
737 ctx->tc_pin_file, errcode,
738 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
742 /* get the file size */
743 if ( PR_SUCCESS != PR_GetFileInfo( ctx->tc_pin_file, &file_info ) ) {
744 PRErrorCode errcode = PR_GetError();
745 Debug( LDAP_DEBUG_ANY,
746 "TLS: could not get file info from pin file %s - error %d:%s.\n",
747 ctx->tc_pin_file, errcode,
748 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
752 /* create a buffer to hold the file contents */
753 if ( !( contents = PR_MALLOC( file_info.size + 1 ) ) ) {
754 PRErrorCode errcode = PR_GetError();
755 Debug( LDAP_DEBUG_ANY,
756 "TLS: could not alloc a buffer for contents of pin file %s - error %d:%s.\n",
757 ctx->tc_pin_file, errcode,
758 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
762 /* read file into the buffer */
763 if( PR_Read( pwd_fileptr, contents, file_info.size ) <= 0 ) {
764 PRErrorCode errcode = PR_GetError();
765 Debug( LDAP_DEBUG_ANY,
766 "TLS: could not read the file contents from pin file %s - error %d:%s.\n",
767 ctx->tc_pin_file, errcode,
768 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
772 /* format is [tokenname:]password EOL [tokenname:]password EOL ... */
773 /* if you want to use a password containing a colon character, use
774 the special tokenname "default" */
775 for ( line = PL_strtok_r( contents, "\r\n", &lasts ); line;
776 line = PL_strtok_r( NULL, "\r\n", &lasts ) ) {
780 continue; /* skip blank lines */
782 colon = PL_strchr( line, ':' );
784 if ( *(colon + 1) && token_name &&
785 !PL_strncmp( token_name, line, colon-line ) ) {
786 candidate = colon + 1; /* found a definite match */
788 } else if ( !PL_strncmp( DEFAULT_TOKEN_NAME, line, colon-line ) ) {
789 candidate = colon + 1; /* found possible match */
791 } else { /* no token name */
797 PR_Close( pwd_fileptr );
800 pwdstr = PL_strdup( candidate );
802 PL_strfree( contents );
806 #endif /* READ_PASSWORD_FROM_FILE */
808 #ifdef READ_PASSWORD_FROM_STDIN
810 * Turn the echoing off on a tty.
815 if ( isatty( fd ) ) {
817 tcgetattr( fd, &tio );
818 tio.c_lflag &= ~ECHO;
819 tcsetattr( fd, TCSAFLUSH, &tio );
824 * Turn the echoing on on a tty.
829 if ( isatty( fd ) ) {
831 tcgetattr( fd, &tio );
833 tcsetattr( fd, TCSAFLUSH, &tio );
834 tcsetattr( fd, TCSAFLUSH, &tio );
837 #endif /* READ_PASSWORD_FROM_STDIN */
840 * This does the actual work of reading the pin/password/pass phrase
843 tlsm_get_pin(PK11SlotInfo *slot, PRBool retry, tlsm_ctx *ctx)
845 char *token_name = NULL;
848 token_name = PK11_GetTokenName( slot );
849 #ifdef READ_PASSWORD_FROM_FILE
850 /* Try to get the passwords from the password file if it exists.
851 * THIS IS UNSAFE and is provided for convenience only. Without this
852 * capability the server would have to be started in foreground mode
853 * if using an encrypted key.
855 if ( ctx->tc_pin_file ) {
856 pwdstr = tlsm_get_pin_from_file( token_name, ctx );
858 #endif /* RETRIEVE_PASSWORD_FROM_FILE */
859 #ifdef READ_PASSWORD_FROM_STDIN
861 int infd = PR_FileDesc2NativeHandle( PR_STDIN );
862 int isTTY = isatty( infd );
863 unsigned char phrase[200];
864 /* Prompt for password */
867 "Please enter pin, password, or pass phrase for security token '%s': ",
868 token_name ? token_name : DEFAULT_TOKEN_NAME );
871 fgets( (char*)phrase, sizeof(phrase), stdin );
873 fprintf( stdout, "\n" );
876 /* stomp on newline */
877 phrase[strlen((char*)phrase)-1] = 0;
879 pwdstr = PL_strdup( (char*)phrase );
882 #endif /* READ_PASSWORD_FROM_STDIN */
887 * PKCS11 devices (including the internal softokn cert/key database)
888 * may be protected by a pin or password or even pass phrase
889 * MozNSS needs a way for the user to provide that
892 tlsm_pin_prompt(PK11SlotInfo *slot, PRBool retry, void *arg)
894 tlsm_ctx *ctx = (tlsm_ctx *)arg;
896 return tlsm_get_pin( slot, retry, ctx );
900 tlsm_get_basic_constraint_extension( CERTCertificate *cert,
901 CERTBasicConstraints *cbcval )
903 SECItem encodedVal = { 0, NULL };
906 rc = CERT_FindCertExtension( cert, SEC_OID_X509_BASIC_CONSTRAINTS,
908 if ( rc != SECSuccess ) {
912 rc = CERT_DecodeBasicConstraintValue( cbcval, &encodedVal );
914 /* free the raw extension data */
915 PORT_Free( encodedVal.data );
921 tlsm_cert_is_self_issued( CERTCertificate *cert )
923 /* A cert is self-issued if its subject and issuer are equal and
924 * both are of non-zero length.
926 PRBool is_self_issued = cert &&
927 (PRBool)SECITEM_ItemsAreEqual( &cert->derIssuer,
928 &cert->derSubject ) &&
929 cert->derSubject.len > 0;
930 return is_self_issued;
934 tlsm_verify_cert(CERTCertDBHandle *handle, CERTCertificate *cert, void *pinarg,
935 PRBool checksig, SECCertUsage certUsage, int errorToIgnore )
937 CERTVerifyLog verifylog;
938 SECStatus ret = SECSuccess;
941 /* the log captures information about every cert in the chain, so we can tell
942 which cert caused the problem and what the problem was */
943 memset( &verifylog, 0, sizeof( verifylog ) );
944 verifylog.arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE );
945 if ( verifylog.arena == NULL ) {
946 Debug( LDAP_DEBUG_ANY,
947 "TLS certificate verification: Out of memory for certificate verification logger\n",
951 ret = CERT_VerifyCertificate( handle, cert, checksig, certUsage, PR_Now(), pinarg, &verifylog,
953 if ( ( name = cert->subjectName ) == NULL ) {
954 name = cert->nickname;
956 if ( verifylog.head == NULL ) {
957 /* it is possible for CERT_VerifyCertificate return with an error with no logging */
958 if ( ret != SECSuccess ) {
959 PRErrorCode errcode = PR_GetError();
960 Debug( LDAP_DEBUG_ANY,
961 "TLS: certificate [%s] is not valid - error %d:%s.\n",
962 name ? name : "(unknown)",
963 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
967 CERTVerifyLogNode *node;
969 ret = SECSuccess; /* reset */
970 node = verifylog.head;
972 if ( ( name = node->cert->subjectName ) == NULL ) {
973 name = node->cert->nickname;
976 /* NSS does not like CA certs that have the basic constraints extension
977 with the CA flag set to FALSE - openssl doesn't check if the cert
979 if ( ( node->error == SEC_ERROR_CA_CERT_INVALID ) &&
980 tlsm_cert_is_self_issued( node->cert ) ) {
981 CERTBasicConstraints basicConstraint;
982 SECStatus rv = tlsm_get_basic_constraint_extension( node->cert, &basicConstraint );
983 if ( ( rv == SECSuccess ) && ( basicConstraint.isCA == PR_FALSE ) ) {
984 Debug( LDAP_DEBUG_TRACE,
985 "TLS: certificate [%s] is not correct because it is a CA cert and the "
986 "BasicConstraint CA flag is set to FALSE - allowing for now, but "
987 "please fix your certs if possible\n", name, 0, 0 );
988 } else { /* does not have basicconstraint, or some other error */
990 Debug( LDAP_DEBUG_ANY,
991 "TLS: certificate [%s] is not valid - CA cert is not valid\n",
994 } else if ( errorToIgnore && ( node->error == errorToIgnore ) ) {
995 Debug( LDAP_DEBUG_ANY,
996 "TLS: Warning: ignoring error for certificate [%s] - error %ld:%s.\n",
997 name, node->error, PR_ErrorToString( node->error, PR_LANGUAGE_I_DEFAULT ) );
1000 Debug( LDAP_DEBUG_ANY,
1001 "TLS: certificate [%s] is not valid - error %ld:%s.\n",
1002 name, node->error, PR_ErrorToString( node->error, PR_LANGUAGE_I_DEFAULT ) );
1005 CERT_DestroyCertificate( node->cert );
1010 PORT_FreeArena( verifylog.arena, PR_FALSE );
1012 if ( ret == SECSuccess ) {
1013 Debug( LDAP_DEBUG_TRACE,
1014 "TLS: certificate [%s] is valid\n", name, 0, 0 );
1021 tlsm_auth_cert_handler(void *arg, PRFileDesc *fd,
1022 PRBool checksig, PRBool isServer)
1024 SECCertUsage certUsage = isServer ? certUsageSSLClient : certUsageSSLServer;
1025 SECStatus ret = SECSuccess;
1027 ret = tlsm_verify_cert( (CERTCertDBHandle *)arg, SSL_PeerCertificate( fd ),
1028 SSL_RevealPinArg( fd ),
1029 checksig, certUsage, 0 );
1035 tlsm_authenticate_to_slot( tlsm_ctx *ctx, PK11SlotInfo *slot )
1039 if ( SECSuccess != PK11_Authenticate( slot, PR_FALSE, ctx ) ) {
1040 char *token_name = PK11_GetTokenName( slot );
1041 PRErrorCode errcode = PR_GetError();
1042 Debug( LDAP_DEBUG_ANY,
1043 "TLS: could not authenticate to the security token %s - error %d:%s.\n",
1044 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1045 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1047 rc = 0; /* success */
1054 tlsm_nss_shutdown_cb( void *appData, void *nssData )
1056 SECStatus rc = SECSuccess;
1058 SSL_ShutdownServerSessionIDCache();
1059 SSL_ClearSessionCache();
1062 SECMOD_UnloadUserModule( pem_module );
1063 SECMOD_DestroyModule( pem_module );
1070 tlsm_init_pem_module( void )
1073 char *fullname = NULL;
1074 char *configstring = NULL;
1080 /* not loaded - load it */
1081 /* get the system dependent library name */
1082 fullname = PR_GetLibraryName( NULL, PEM_LIBRARY );
1083 /* Load our PKCS#11 module */
1084 configstring = PR_smprintf( "library=%s name=" PEM_MODULE " parameters=\"\"", fullname );
1085 PL_strfree( fullname );
1087 pem_module = SECMOD_LoadUserModule( configstring, NULL, PR_FALSE );
1088 PR_smprintf_free( configstring );
1090 if ( !pem_module || !pem_module->loaded ) {
1092 SECMOD_DestroyModule( pem_module );
1102 tlsm_add_pem_obj( tlsm_ctx *ctx, PK11GenericObject *obj )
1104 int idx = ctx->tc_n_pem_objs;
1105 ctx->tc_n_pem_objs++;
1106 ctx->tc_pem_objs = (PK11GenericObject **)
1107 PORT_Realloc( ctx->tc_pem_objs, ctx->tc_n_pem_objs * sizeof( PK11GenericObject * ) );
1108 ctx->tc_pem_objs[idx] = obj;
1112 tlsm_free_pem_objs( tlsm_ctx *ctx )
1114 /* free in reverse order of allocation */
1115 while ( ctx->tc_n_pem_objs-- ) {
1116 PK11_DestroyGenericObject( ctx->tc_pem_objs[ctx->tc_n_pem_objs] );
1117 ctx->tc_pem_objs[ctx->tc_n_pem_objs] = NULL;
1119 PORT_Free(ctx->tc_pem_objs);
1120 ctx->tc_pem_objs = NULL;
1121 ctx->tc_n_pem_objs = 0;
1125 tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca, PRBool istrusted )
1128 PK11SlotInfo *slot = NULL;
1129 PK11GenericObject *rv;
1130 CK_ATTRIBUTE *attrs;
1131 CK_ATTRIBUTE theTemplate[20];
1132 CK_BBOOL cktrue = CK_TRUE;
1133 CK_BBOOL ckfalse = CK_FALSE;
1134 CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
1135 char tmpslotname[64];
1136 char *slotname = NULL;
1137 const char *ptr = NULL;
1138 char sep = PR_GetDirectorySeparator();
1142 memset( &fi, 0, sizeof(fi) );
1143 status = PR_GetFileInfo( filename, &fi );
1144 if ( PR_SUCCESS != status) {
1145 PRErrorCode errcode = PR_GetError();
1146 Debug( LDAP_DEBUG_ANY,
1147 "TLS: could not read certificate file %s - error %d:%s.\n",
1149 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1153 if ( fi.type != PR_FILE_FILE ) {
1154 PR_SetError(PR_IS_DIRECTORY_ERROR, 0);
1155 Debug( LDAP_DEBUG_ANY,
1156 "TLS: error: the certificate file %s is not a file.\n",
1161 attrs = theTemplate;
1164 slotID = 0; /* CA and trust objects use slot 0 */
1165 PR_snprintf( tmpslotname, sizeof(tmpslotname), TLSM_PEM_TOKEN_FMT, slotID );
1166 slotname = tmpslotname;
1167 istrusted = PR_TRUE;
1169 if ( ctx->tc_slotname == NULL ) { /* need new slot */
1173 slotID = ++tlsm_slot_count;
1175 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
1177 slotname = ctx->tc_slotname;
1179 if ( ( ptr = PL_strrchr( filename, sep ) ) ) {
1180 PL_strfree( ctx->tc_certname );
1183 /* pemnss conflates trusted certs with CA certs - since there can
1184 be more than one CA cert in a file (e.g. ca-bundle.crt) pemnss
1185 numbers each trusted cert - in the case of a server cert, there will be
1186 only one, so it will be number 0 */
1187 ctx->tc_certname = PR_smprintf( "%s:%s - 0", slotname, ptr );
1189 ctx->tc_certname = PR_smprintf( "%s:%s", slotname, ptr );
1194 slot = PK11_FindSlotByName( slotname );
1197 PRErrorCode errcode = PR_GetError();
1198 Debug( LDAP_DEBUG_ANY,
1199 "TLS: could not find the slot for certificate %s - error %d:%s.\n",
1200 ctx->tc_certname, errcode,
1201 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1205 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1206 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1207 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1209 PK11_SETATTRS( attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1211 PK11_SETATTRS( attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) ); attrs++;
1213 /* This loads the certificate in our PEM module into the appropriate
1216 rv = PK11_CreateGenericObject( slot, theTemplate, 4, PR_FALSE /* isPerm */ );
1218 PK11_FreeSlot( slot );
1221 PRErrorCode errcode = PR_GetError();
1222 Debug( LDAP_DEBUG_ANY,
1223 "TLS: could not add the certificate %s - error %d:%s.\n",
1224 ctx->tc_certname, errcode,
1225 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1229 tlsm_add_pem_obj( ctx, rv );
1235 tlsm_add_key_from_file( tlsm_ctx *ctx, const char *filename )
1238 PK11SlotInfo * slot = NULL;
1239 PK11GenericObject *rv;
1240 CK_ATTRIBUTE *attrs;
1241 CK_ATTRIBUTE theTemplate[20];
1242 CK_BBOOL cktrue = CK_TRUE;
1243 CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
1248 memset( &fi, 0, sizeof(fi) );
1249 status = PR_GetFileInfo( filename, &fi );
1250 if ( PR_SUCCESS != status) {
1251 PRErrorCode errcode = PR_GetError();
1252 Debug( LDAP_DEBUG_ANY,
1253 "TLS: could not read key file %s - error %d:%s.\n",
1255 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1259 if ( fi.type != PR_FILE_FILE ) {
1260 PR_SetError(PR_IS_DIRECTORY_ERROR, 0);
1261 Debug( LDAP_DEBUG_ANY,
1262 "TLS: error: the key file %s is not a file.\n",
1267 attrs = theTemplate;
1269 if ( ctx->tc_slotname == NULL ) { /* need new slot */
1270 slotID = ++tlsm_slot_count;
1271 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
1273 slot = PK11_FindSlotByName( ctx->tc_slotname );
1276 PRErrorCode errcode = PR_GetError();
1277 Debug( LDAP_DEBUG_ANY,
1278 "TLS: could not find the slot %s for the private key - error %d:%s.\n",
1279 ctx->tc_slotname, errcode,
1280 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1284 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1285 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1286 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1287 rv = PK11_CreateGenericObject( slot, theTemplate, 3, PR_FALSE /* isPerm */ );
1290 PRErrorCode errcode = PR_GetError();
1291 Debug( LDAP_DEBUG_ANY,
1292 "TLS: could not add the certificate %s - error %d:%s.\n",
1293 ctx->tc_certname, errcode,
1294 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1297 /* When adding an encrypted key the PKCS#11 will be set as removed */
1298 /* This will force the token to be seen as re-inserted */
1299 SECMOD_WaitForAnyTokenEvent( pem_module, 0, 0 );
1300 PK11_IsPresent( slot );
1304 PK11_FreeSlot( slot );
1307 tlsm_add_pem_obj( ctx, rv );
1313 tlsm_init_ca_certs( tlsm_ctx *ctx, const char *cacertfile, const char *cacertdir )
1315 PRBool isca = PR_TRUE;
1316 PRStatus status = PR_FAILURE;
1317 PRErrorCode errcode = PR_SUCCESS;
1319 if ( !cacertfile && !cacertdir ) {
1320 /* no checking - not good, but allowed */
1325 int rc = tlsm_add_cert_from_file( ctx, cacertfile, isca, PR_TRUE );
1327 errcode = PR_GetError();
1328 Debug( LDAP_DEBUG_ANY,
1329 "TLS: %s is not a valid CA certificate file - error %d:%s.\n",
1330 cacertfile, errcode,
1331 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1333 Debug( LDAP_DEBUG_TRACE,
1334 "TLS: loaded CA certificate file %s.\n",
1336 status = PR_SUCCESS; /* have at least one good CA - we can proceed */
1344 PRStatus fistatus = PR_FAILURE;
1346 memset( &fi, 0, sizeof(fi) );
1347 fistatus = PR_GetFileInfo( cacertdir, &fi );
1348 if ( PR_SUCCESS != fistatus) {
1349 errcode = PR_GetError();
1350 Debug( LDAP_DEBUG_ANY,
1351 "TLS: could not get info about the CA certificate directory %s - error %d:%s.\n",
1353 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1357 if ( fi.type != PR_FILE_DIRECTORY ) {
1358 Debug( LDAP_DEBUG_ANY,
1359 "TLS: error: the CA certificate directory %s is not a directory.\n",
1364 dir = PR_OpenDir( cacertdir );
1365 if ( NULL == dir ) {
1366 errcode = PR_GetError();
1367 Debug( LDAP_DEBUG_ANY,
1368 "TLS: could not open the CA certificate directory %s - error %d:%s.\n",
1370 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1375 entry = PR_ReadDir( dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN );
1376 if ( ( NULL != entry ) && ( NULL != entry->name ) ) {
1377 char *fullpath = NULL;
1380 ptr = PL_strrstr( entry->name, PEM_CA_HASH_FILE_SUFFIX );
1381 if ( ( ptr == NULL ) || ( *(ptr + PEM_CA_HASH_FILE_SUFFIX_LEN) != '\0' ) ) {
1382 Debug( LDAP_DEBUG_TRACE,
1383 "TLS: file %s does not end in [%s] - does not appear to be a CA certificate "
1384 "directory file with a properly hashed file name - skipping.\n",
1385 entry->name, PEM_CA_HASH_FILE_SUFFIX, 0 );
1388 fullpath = PR_smprintf( "%s/%s", cacertdir, entry->name );
1389 if ( !tlsm_add_cert_from_file( ctx, fullpath, isca, PR_TRUE ) ) {
1390 Debug( LDAP_DEBUG_TRACE,
1391 "TLS: loaded CA certificate file %s from CA certificate directory %s.\n",
1392 fullpath, cacertdir, 0 );
1393 status = PR_SUCCESS; /* found at least 1 valid CA file in the dir */
1395 errcode = PR_GetError();
1396 Debug( LDAP_DEBUG_TRACE,
1397 "TLS: %s is not a valid CA certificate file - error %d:%s.\n",
1399 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1401 PR_smprintf_free( fullpath );
1403 } while ( NULL != entry );
1407 if ( status != PR_SUCCESS ) {
1408 const char *fmtstr = NULL;
1409 if ( cacertfile && cacertdir ) {
1410 fmtstr = "TLS: did not find any valid CA certificates in %s or %s\n";
1412 fmtstr = "TLS: did not find any valid CA certificates in %s%s\n";
1414 Debug( LDAP_DEBUG_ANY, fmtstr, cacertdir ? cacertdir : "",
1415 cacertfile ? cacertfile : "", 0 );
1423 * NSS supports having multiple cert/key databases in the same
1424 * directory, each one having a unique string prefix e.g.
1425 * slapd-01-cert8.db - the prefix here is "slapd-01-"
1426 * this function examines the given certdir - if it looks like
1427 * /path/to/directory/prefix it will return the
1428 * /path/to/directory part in realcertdir, and the prefix in prefix
1431 tlsm_get_certdb_prefix( const char *certdir, char **realcertdir, char **prefix )
1433 char sep = PR_GetDirectorySeparator();
1435 struct PRFileInfo prfi;
1438 *realcertdir = (char *)certdir; /* default is the one passed in */
1440 /* if certdir is not given, just return */
1445 prc = PR_GetFileInfo( certdir, &prfi );
1446 /* if certdir exists (file or directory) then it cannot specify a prefix */
1447 if ( prc == PR_SUCCESS ) {
1451 /* if certdir was given, and there is a '/' in certdir, see if there
1452 is anything after the last '/' - if so, assume it is the prefix */
1453 if ( ( ( ptr = strrchr( certdir, sep ) ) ) && *(ptr+1) ) {
1454 *realcertdir = PL_strndup( certdir, ptr-certdir );
1455 *prefix = PL_strdup( ptr+1 );
1462 * This is the part of the init we defer until we get the
1463 * actual security configuration information. This is
1464 * only called once, protected by a PRCallOnce
1465 * NOTE: This must be done before the first call to SSL_ImportFD,
1466 * especially the setting of the policy
1467 * NOTE: This must be called after fork()
1470 tlsm_deferred_init( void *arg )
1472 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1473 struct ldaptls *lt = ctx->tc_config;
1474 const char *securitydirs[3];
1477 PRErrorCode errcode = 1;
1478 #ifdef HAVE_NSS_INITCONTEXT
1479 NSSInitParameters initParams;
1480 NSSInitContext *initctx = NULL;
1485 #ifdef HAVE_NSS_INITCONTEXT
1486 memset( &initParams, 0, sizeof( initParams ) );
1487 initParams.length = sizeof( initParams );
1488 #endif /* HAVE_NSS_INITCONTEXT */
1490 #ifndef HAVE_NSS_INITCONTEXT
1491 if ( !NSS_IsInitialized() ) {
1492 #endif /* HAVE_NSS_INITCONTEXT */
1494 MOZNSS_DIR will override everything else - you can
1495 always set MOZNSS_DIR to force the use of this
1497 If using MOZNSS, specify the location of the moznss db dir
1498 in the cacertdir directive of the OpenLDAP configuration.
1499 DEFAULT_MOZNSS_DIR will only be used if the code cannot
1500 find a security dir to use based on the current
1504 securitydirs[nn++] = PR_GetEnv( "MOZNSS_DIR" );
1505 securitydirs[nn++] = lt->lt_cacertdir;
1506 securitydirs[nn++] = PR_GetEnv( "DEFAULT_MOZNSS_DIR" );
1507 for ( ii = 0; !done && ( ii < nn ); ++ii ) {
1508 char *realcertdir = NULL;
1509 const char *defprefix = "";
1510 char *prefix = (char *)defprefix;
1511 const char *securitydir = securitydirs[ii];
1512 if ( NULL == securitydir ) {
1516 tlsm_get_certdb_prefix( securitydir, &realcertdir, &prefix );
1517 #ifdef HAVE_NSS_INITCONTEXT
1518 #ifdef INITCONTEXT_HACK
1519 if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
1520 rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
1522 initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
1523 &initParams, NSS_INIT_READONLY );
1524 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1527 initctx = NSS_InitContext( realcertdir, prefix, prefix, SECMOD_DB,
1528 &initParams, NSS_INIT_READONLY );
1529 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1532 rc = NSS_Initialize( realcertdir, prefix, prefix, SECMOD_DB, NSS_INIT_READONLY );
1535 if ( rc != SECSuccess ) {
1536 errcode = PORT_GetError();
1537 if ( securitydirs[ii] != lt->lt_cacertdir) {
1538 Debug( LDAP_DEBUG_TRACE,
1539 "TLS: could not initialize moznss using security dir %s prefix %s - error %d.\n",
1540 realcertdir, prefix, errcode );
1544 Debug( LDAP_DEBUG_TRACE, "TLS: using moznss security dir %s prefix %s.\n",
1545 realcertdir, prefix, 0 );
1549 if ( realcertdir != securitydir ) {
1550 PL_strfree( realcertdir );
1552 if ( prefix != defprefix ) {
1553 PL_strfree( prefix );
1557 if ( errcode ) { /* no moznss db found, or not using moznss db */
1558 #ifdef HAVE_NSS_INITCONTEXT
1559 int flags = NSS_INIT_READONLY|NSS_INIT_NOCERTDB|NSS_INIT_NOMODDB;
1560 #ifdef INITCONTEXT_HACK
1561 if ( !NSS_IsInitialized() && ctx->tc_is_server ) {
1562 rc = NSS_NoDB_Init( NULL );
1564 initctx = NSS_InitContext( "", "", "", SECMOD_DB,
1565 &initParams, flags );
1566 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1569 initctx = NSS_InitContext( "", "", "", SECMOD_DB,
1570 &initParams, flags );
1571 rc = (initctx == NULL) ? SECFailure : SECSuccess;
1574 rc = NSS_NoDB_Init( NULL );
1576 if ( rc != SECSuccess ) {
1577 errcode = PORT_GetError();
1578 Debug( LDAP_DEBUG_ANY,
1579 "TLS: could not initialize moznss - error %d:%s.\n",
1580 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1584 #ifdef HAVE_NSS_INITCONTEXT
1585 ctx->tc_initctx = initctx;
1588 /* initialize the PEM module */
1589 if ( tlsm_init_pem_module() ) {
1590 errcode = PORT_GetError();
1591 Debug( LDAP_DEBUG_ANY,
1592 "TLS: could not initialize moznss PEM module - error %d:%s.\n",
1593 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1597 if ( tlsm_init_ca_certs( ctx, lt->lt_cacertfile, lt->lt_cacertdir ) ) {
1598 /* if we tried to use lt->lt_cacertdir as an NSS key/cert db, errcode
1599 will be a value other than 1 - print an error message so that the
1600 user will know that failed too */
1601 if ( ( errcode != 1 ) && ( lt->lt_cacertdir ) ) {
1602 char *realcertdir = NULL;
1603 char *prefix = NULL;
1604 tlsm_get_certdb_prefix( lt->lt_cacertdir, &realcertdir, &prefix );
1605 Debug( LDAP_DEBUG_TRACE,
1606 "TLS: could not initialize moznss using security dir %s prefix %s - error %d.\n",
1607 realcertdir, prefix ? prefix : "", errcode );
1608 if ( realcertdir != lt->lt_cacertdir ) {
1609 PL_strfree( realcertdir );
1611 PL_strfree( prefix );
1616 ctx->tc_using_pem = PR_TRUE;
1619 #ifdef HAVE_NSS_INITCONTEXT
1620 if ( !ctx->tc_initctx ) {
1621 ctx->tc_initctx = initctx;
1625 NSS_SetDomesticPolicy();
1627 PK11_SetPasswordFunc( tlsm_pin_prompt );
1629 /* register cleanup function */
1630 /* delete the old one, if any */
1631 NSS_UnregisterShutdown( tlsm_nss_shutdown_cb, NULL );
1632 NSS_RegisterShutdown( tlsm_nss_shutdown_cb, NULL );
1634 #ifndef HAVE_NSS_INITCONTEXT
1636 #endif /* HAVE_NSS_INITCONTEXT */
1642 tlsm_authenticate( tlsm_ctx *ctx, const char *certname, const char *pininfo )
1644 const char *colon = NULL;
1645 char *token_name = NULL;
1646 PK11SlotInfo *slot = NULL;
1649 if ( !certname || !*certname ) {
1653 if ( ( colon = PL_strchr( certname, ':' ) ) ) {
1654 token_name = PL_strndup( certname, colon-certname );
1658 slot = PK11_FindSlotByName( token_name );
1660 slot = PK11_GetInternalKeySlot();
1664 PRErrorCode errcode = PR_GetError();
1665 Debug( LDAP_DEBUG_ANY,
1666 "TLS: could not find the slot for security token %s - error %d:%s.\n",
1667 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1668 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1672 rc = tlsm_authenticate_to_slot( ctx, slot );
1675 PL_strfree( token_name );
1677 PK11_FreeSlot( slot );
1684 * Find and verify the certificate.
1685 * Either fd is given, in which case the cert will be taken from it via SSL_PeerCertificate
1686 * or certname is given, and it will be searched for by name
1689 tlsm_find_and_verify_cert_key(tlsm_ctx *ctx, PRFileDesc *fd, const char *certname, int isServer, CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey)
1691 CERTCertificate *cert = NULL;
1693 void *pin_arg = NULL;
1694 SECKEYPrivateKey *key = NULL;
1696 pin_arg = SSL_RevealPinArg( fd );
1698 cert = PK11_FindCertFromNickname( certname, pin_arg );
1700 PRErrorCode errcode = PR_GetError();
1701 Debug( LDAP_DEBUG_ANY,
1702 "TLS: error: the certificate %s could not be found in the database - error %d:%s\n",
1703 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1707 /* we are verifying the peer cert
1708 we also need to swap the isServer meaning */
1709 cert = SSL_PeerCertificate( fd );
1711 PRErrorCode errcode = PR_GetError();
1712 Debug( LDAP_DEBUG_ANY,
1713 "TLS: error: could not get the certificate from the peer connection - error %d:%s\n",
1714 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), NULL );
1717 isServer = !isServer; /* verify the peer's cert instead */
1720 if ( ctx->tc_slotname ) {
1721 PK11SlotInfo *slot = PK11_FindSlotByName( ctx->tc_slotname );
1722 key = PK11_FindPrivateKeyFromCert( slot, cert, NULL );
1723 PK11_FreeSlot( slot );
1725 key = PK11_FindKeyByAnyCert( cert, pin_arg );
1729 SECCertificateUsage certUsage;
1730 PRBool checkSig = PR_TRUE;
1734 *pRetKey = key; /* caller will deal with this */
1736 SECKEY_DestroyPrivateKey( key );
1739 certUsage = certificateUsageSSLServer;
1741 certUsage = certificateUsageSSLClient;
1743 if ( ctx->tc_verify_cert ) {
1746 checkSig = PR_FALSE;
1748 /* may not have a CA cert - ok - ignore SEC_ERROR_UNKNOWN_ISSUER */
1749 status = tlsm_verify_cert( ctx->tc_certdb, cert, pin_arg,
1750 checkSig, certUsage, SEC_ERROR_UNKNOWN_ISSUER );
1751 if ( status == SECSuccess ) {
1755 PRErrorCode errcode = PR_GetError();
1756 Debug( LDAP_DEBUG_ANY,
1757 "TLS: error: could not find the private key for certificate %s - error %d:%s\n",
1758 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1762 *pRetCert = cert; /* caller will deal with this */
1764 CERT_DestroyCertificate( cert );
1771 tlsm_get_client_auth_data( void *arg, PRFileDesc *fd,
1772 CERTDistNames *caNames, CERTCertificate **pRetCert,
1773 SECKEYPrivateKey **pRetKey )
1775 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1778 /* don't need caNames - this function will call CERT_VerifyCertificateNow
1779 which will verify the cert against the known CAs */
1780 rc = tlsm_find_and_verify_cert_key( ctx, fd, ctx->tc_certname, 0, pRetCert, pRetKey );
1782 Debug( LDAP_DEBUG_ANY,
1783 "TLS: error: unable to perform client certificate authentication for "
1784 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1792 * ctx must have a tc_model that is valid
1793 * certname is in the form [<tokenname>:]<certnickname>
1794 * where <tokenname> is the name of the PKCS11 token
1795 * and <certnickname> is the nickname of the cert/key in
1799 tlsm_clientauth_init( tlsm_ctx *ctx )
1801 SECStatus status = SECFailure;
1804 rc = tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, 0, NULL, NULL );
1806 Debug( LDAP_DEBUG_ANY,
1807 "TLS: error: unable to set up client certificate authentication for "
1808 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1812 status = SSL_GetClientAuthDataHook( ctx->tc_model,
1813 tlsm_get_client_auth_data,
1816 return ( status == SECSuccess ? 0 : -1 );
1820 * Tear down the TLS subsystem. Should only be called once.
1823 tlsm_destroy( void )
1828 tlsm_ctx_new ( struct ldapoptions *lo )
1832 ctx = LDAP_MALLOC( sizeof (*ctx) );
1835 #ifdef LDAP_R_COMPILE
1836 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
1838 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 */
1839 ctx->tc_certdb = NULL;
1840 ctx->tc_certname = NULL;
1841 ctx->tc_pin_file = NULL;
1842 ctx->tc_model = NULL;
1843 memset(&ctx->tc_callonce, 0, sizeof(ctx->tc_callonce));
1844 ctx->tc_require_cert = lo->ldo_tls_require_cert;
1845 ctx->tc_verify_cert = PR_FALSE;
1846 ctx->tc_using_pem = PR_FALSE;
1847 ctx->tc_slotname = NULL;
1848 #ifdef HAVE_NSS_INITCONTEXT
1849 ctx->tc_initctx = NULL;
1850 #endif /* HAVE_NSS_INITCONTEXT */
1851 ctx->tc_pem_objs = NULL;
1852 ctx->tc_n_pem_objs = 0;
1854 return (tls_ctx *)ctx;
1858 tlsm_ctx_ref( tls_ctx *ctx )
1860 tlsm_ctx *c = (tlsm_ctx *)ctx;
1861 LDAP_MUTEX_LOCK( &c->tc_refmutex );
1863 LDAP_MUTEX_UNLOCK( &c->tc_refmutex );
1867 tlsm_ctx_free ( tls_ctx *ctx )
1869 tlsm_ctx *c = (tlsm_ctx *)ctx;
1874 LDAP_MUTEX_LOCK( &c->tc_refmutex );
1875 refcount = --c->tc_refcnt;
1876 LDAP_MUTEX_UNLOCK( &c->tc_refmutex );
1880 PR_Close( c->tc_model );
1881 c->tc_certdb = NULL; /* if not the default, may have to clean up */
1882 PL_strfree( c->tc_certname );
1883 c->tc_certname = NULL;
1884 PL_strfree( c->tc_pin_file );
1885 c->tc_pin_file = NULL;
1886 PL_strfree( c->tc_slotname );
1887 tlsm_free_pem_objs( c );
1888 #ifdef HAVE_NSS_INITCONTEXT
1890 NSS_ShutdownContext( c->tc_initctx );
1891 c->tc_initctx = NULL;
1892 #endif /* HAVE_NSS_INITCONTEXT */
1893 #ifdef LDAP_R_COMPILE
1894 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
1900 * initialize a new TLS context
1903 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
1905 tlsm_ctx *ctx = (tlsm_ctx *)lo->ldo_tls_ctx;
1906 ctx->tc_is_server = is_server;
1912 tlsm_deferred_ctx_init( void *arg )
1914 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1915 PRBool sslv2 = PR_FALSE;
1916 PRBool sslv3 = PR_TRUE;
1917 PRBool tlsv1 = PR_TRUE;
1918 PRBool request_cert = PR_FALSE;
1919 PRInt32 require_cert = PR_FALSE;
1923 if ( tlsm_deferred_init( ctx ) ) {
1924 Debug( LDAP_DEBUG_ANY,
1925 "TLS: could perform TLS system initialization.\n",
1930 ctx->tc_certdb = CERT_GetDefaultCertDB(); /* If there is ever a per-context db, change this */
1932 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
1934 ctx->tc_model = SSL_ImportFD( NULL, fd );
1937 if ( !ctx->tc_model ) {
1938 PRErrorCode err = PR_GetError();
1939 Debug( LDAP_DEBUG_ANY,
1940 "TLS: could perform TLS socket I/O layer initialization - error %d:%s.\n",
1941 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1949 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE ) ) {
1950 Debug( LDAP_DEBUG_ANY,
1951 "TLS: could not set secure mode on.\n",
1956 lt = ctx->tc_config;
1958 /* default is sslv3 and tlsv1 */
1959 if ( lt->lt_protocol_min ) {
1960 if ( lt->lt_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 ) {
1962 } else if ( lt->lt_protocol_min <= LDAP_OPT_X_TLS_PROTOCOL_SSL2 ) {
1964 Debug( LDAP_DEBUG_ANY,
1965 "TLS: warning: minimum TLS protocol level set to "
1966 "include SSLv2 - SSLv2 is insecure - do not use\n", 0, 0, 0 );
1969 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL2, sslv2 ) ) {
1970 Debug( LDAP_DEBUG_ANY,
1971 "TLS: could not set SSLv2 mode on.\n",
1975 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL3, sslv3 ) ) {
1976 Debug( LDAP_DEBUG_ANY,
1977 "TLS: could not set SSLv3 mode on.\n",
1981 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_TLS, tlsv1 ) ) {
1982 Debug( LDAP_DEBUG_ANY,
1983 "TLS: could not set TLSv1 mode on.\n",
1988 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !ctx->tc_is_server ) ) {
1989 Debug( LDAP_DEBUG_ANY,
1990 "TLS: could not set handshake as client.\n",
1994 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, ctx->tc_is_server ) ) {
1995 Debug( LDAP_DEBUG_ANY,
1996 "TLS: could not set handshake as server.\n",
2001 if ( lt->lt_ciphersuite &&
2002 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
2003 Debug( LDAP_DEBUG_ANY,
2004 "TLS: could not set cipher list %s.\n",
2005 lt->lt_ciphersuite, 0, 0 );
2009 if ( ctx->tc_require_cert ) {
2010 request_cert = PR_TRUE;
2011 require_cert = SSL_REQUIRE_NO_ERROR;
2012 if ( ctx->tc_require_cert == LDAP_OPT_X_TLS_DEMAND ||
2013 ctx->tc_require_cert == LDAP_OPT_X_TLS_HARD ) {
2014 require_cert = SSL_REQUIRE_ALWAYS;
2016 if ( ctx->tc_require_cert != LDAP_OPT_X_TLS_ALLOW )
2017 ctx->tc_verify_cert = PR_TRUE;
2019 ctx->tc_verify_cert = PR_FALSE;
2022 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUEST_CERTIFICATE, request_cert ) ) {
2023 Debug( LDAP_DEBUG_ANY,
2024 "TLS: could not set request certificate mode.\n",
2029 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUIRE_CERTIFICATE, require_cert ) ) {
2030 Debug( LDAP_DEBUG_ANY,
2031 "TLS: could not set require certificate mode.\n",
2036 /* set up our cert and key, if any */
2037 if ( lt->lt_certfile ) {
2038 /* if using the PEM module, load the PEM file specified by lt_certfile */
2039 /* otherwise, assume this is the name of a cert already in the db */
2040 if ( ctx->tc_using_pem ) {
2041 /* this sets ctx->tc_certname to the correct value */
2042 int rc = tlsm_add_cert_from_file( ctx, lt->lt_certfile, PR_FALSE, PR_TRUE );
2047 PL_strfree( ctx->tc_certname );
2048 ctx->tc_certname = PL_strdup( lt->lt_certfile );
2052 if ( lt->lt_keyfile ) {
2053 /* if using the PEM module, load the PEM file specified by lt_keyfile */
2054 /* otherwise, assume this is the pininfo for the key */
2055 if ( ctx->tc_using_pem ) {
2056 /* this sets ctx->tc_certname to the correct value */
2057 int rc = tlsm_add_key_from_file( ctx, lt->lt_keyfile );
2062 PL_strfree( ctx->tc_pin_file );
2063 ctx->tc_pin_file = PL_strdup( lt->lt_keyfile );
2067 /* Set up callbacks for use by clients */
2068 if ( !ctx->tc_is_server ) {
2069 if ( SSL_OptionSet( ctx->tc_model, SSL_NO_CACHE, PR_TRUE ) != SECSuccess ) {
2070 PRErrorCode err = PR_GetError();
2071 Debug( LDAP_DEBUG_ANY,
2072 "TLS: error: could not set nocache option for moznss - error %d:%s\n",
2073 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2077 if ( SSL_BadCertHook( ctx->tc_model, tlsm_bad_cert_handler, ctx ) != SECSuccess ) {
2078 PRErrorCode err = PR_GetError();
2079 Debug( LDAP_DEBUG_ANY,
2080 "TLS: error: could not set bad cert handler for moznss - error %d:%s\n",
2081 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2086 since a cert has been specified, assume the client wants to do cert auth
2088 if ( ctx->tc_certname ) {
2089 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
2090 Debug( LDAP_DEBUG_ANY,
2091 "TLS: error: unable to authenticate to the security device for certificate %s\n",
2092 ctx->tc_certname, 0, 0 );
2095 if ( tlsm_clientauth_init( ctx ) ) {
2096 Debug( LDAP_DEBUG_ANY,
2097 "TLS: error: unable to set up client certificate authentication using %s\n",
2098 ctx->tc_certname, 0, 0 );
2102 } else { /* set up secure server */
2104 CERTCertificate *serverCert;
2105 SECKEYPrivateKey *serverKey;
2108 /* must have a certificate for the server to use */
2109 if ( !ctx->tc_certname ) {
2110 Debug( LDAP_DEBUG_ANY,
2111 "TLS: error: no server certificate: must specify a certificate for the server to use\n",
2116 /* authenticate to the server's token - this will do nothing
2117 if the key/cert db is not password protected */
2118 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
2119 Debug( LDAP_DEBUG_ANY,
2120 "TLS: error: unable to authenticate to the security device for certificate %s\n",
2121 ctx->tc_certname, 0, 0 );
2125 /* get the server's key and cert */
2126 if ( tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, ctx->tc_is_server,
2127 &serverCert, &serverKey ) ) {
2128 Debug( LDAP_DEBUG_ANY,
2129 "TLS: error: unable to find and verify server's cert and key for certificate %s\n",
2130 ctx->tc_certname, 0, 0 );
2134 certKEA = NSS_FindCertKEAType( serverCert );
2135 /* configure the socket to be a secure server socket */
2136 status = SSL_ConfigSecureServer( ctx->tc_model, serverCert, serverKey, certKEA );
2137 /* SSL_ConfigSecureServer copies these */
2138 CERT_DestroyCertificate( serverCert );
2139 SECKEY_DestroyPrivateKey( serverKey );
2141 if ( SECSuccess != status ) {
2142 PRErrorCode err = PR_GetError();
2143 Debug( LDAP_DEBUG_ANY,
2144 "TLS: error: unable to configure secure server using certificate %s - error %d:%s\n",
2145 ctx->tc_certname, err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) );
2150 /* Callback for authenticating certificate */
2151 if ( SSL_AuthCertificateHook( ctx->tc_model, tlsm_auth_cert_handler,
2152 ctx->tc_certdb ) != SECSuccess ) {
2153 PRErrorCode err = PR_GetError();
2154 Debug( LDAP_DEBUG_ANY,
2155 "TLS: error: could not set auth cert handler for moznss - error %d:%s\n",
2156 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2160 if ( SSL_HandshakeCallback( ctx->tc_model, tlsm_handshake_complete_cb, ctx ) ) {
2161 PRErrorCode err = PR_GetError();
2162 Debug( LDAP_DEBUG_ANY,
2163 "TLS: error: could not set handshake callback for moznss - error %d:%s\n",
2164 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
2172 tlsm_session *session;
2173 Sockbuf_IO_Desc *sbiod;
2174 /* there seems to be no portable way to determine if the
2175 sockbuf sd has been set to nonblocking mode - the
2176 call to ber_pvt_socket_set_nonblock() takes place
2177 before the tls socket is set up, so we cannot
2178 intercept that call either.
2179 On systems where fcntl is available, we can just
2180 F_GETFL and test for O_NONBLOCK. On other systems,
2181 we will just see if the IO op returns EAGAIN or EWOULDBLOCK,
2182 and just set this flag */
2185 * NSS tries hard to be backwards compatible with SSLv2 clients, or
2186 * clients that send an SSLv2 client hello. This message is not
2187 * tagged in any way, so NSS has no way to know if the incoming
2188 * message is a valid SSLv2 client hello or just some bogus data
2189 * (or cleartext LDAP). We store the first byte read from the
2190 * client here. The most common case will be a client sending
2191 * LDAP data instead of SSL encrypted LDAP data. This can happen,
2192 * for example, if using ldapsearch -Z - if the starttls fails,
2193 * the client will fallback to plain cleartext LDAP. So if we
2194 * see that the firstbyte is a valid LDAP tag, we can be
2195 * pretty sure this is happening.
2199 * NSS doesn't return SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, etc.
2200 * when it is blocked, so we have to set a flag in the wrapped send
2201 * and recv calls that tells us what operation NSS was last blocked
2205 #define TLSM_WRITE 2
2209 static struct tls_data *
2210 tlsm_get_pvt_tls_data( PRFileDesc *fd )
2219 myfd = PR_GetIdentitiesLayer( fd, tlsm_layer_id );
2225 p = (struct tls_data *)myfd->secret;
2231 tlsm_is_non_ssl_message( PRFileDesc *fd, ber_tag_t *thebyte )
2236 *thebyte = LBER_DEFAULT;
2239 p = tlsm_get_pvt_tls_data( fd );
2240 if ( p == NULL || p->sbiod == NULL ) {
2244 if ( p->firsttag == LBER_SEQUENCE ) {
2246 *thebyte = p->firsttag;
2254 static tls_session *
2255 tlsm_session_new ( tls_ctx * ctx, int is_server )
2257 tlsm_ctx *c = (tlsm_ctx *)ctx;
2258 tlsm_session *session;
2263 c->tc_is_server = is_server;
2264 status = PR_CallOnceWithArg( &c->tc_callonce, tlsm_deferred_ctx_init, c );
2265 if ( PR_SUCCESS != status ) {
2266 PRErrorCode err = PR_GetError();
2267 Debug( LDAP_DEBUG_ANY,
2268 "TLS: error: could not initialize moznss security context - error %d:%s\n",
2269 err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT), NULL );
2273 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
2278 session = SSL_ImportFD( c->tc_model, fd );
2285 /* 0 means use the defaults here */
2286 SSL_ConfigServerSessionIDCache( 0, 0, 0, NULL );
2289 rc = SSL_ResetHandshake( session, is_server );
2291 PRErrorCode err = PR_GetError();
2292 Debug( LDAP_DEBUG_TRACE,
2293 "TLS: error: new session - reset handshake failure %d - error %d:%s\n",
2295 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
2297 PR_Close( session );
2301 return (tls_session *)session;
2305 tlsm_session_accept_or_connect( tls_session *session, int is_accept )
2307 tlsm_session *s = (tlsm_session *)session;
2308 int rc = SSL_ForceHandshake( s );
2309 const char *op = is_accept ? "accept" : "connect";
2312 PRErrorCode err = PR_GetError();
2314 if ( err == PR_WOULD_BLOCK_ERROR ) {
2315 ber_tag_t thetag = LBER_DEFAULT;
2316 /* see if we are blocked because of a bogus packet */
2317 if ( tlsm_is_non_ssl_message( s, &thetag ) ) { /* see if we received a non-SSL message */
2318 Debug( LDAP_DEBUG_ANY,
2319 "TLS: error: %s - error - received non-SSL message [0x%x]\n",
2320 op, (unsigned int)thetag, 0 );
2321 /* reset error to something more descriptive */
2322 PR_SetError( SSL_ERROR_RX_MALFORMED_HELLO_REQUEST, EPROTO );
2325 Debug( LDAP_DEBUG_ANY,
2326 "TLS: error: %s - force handshake failure: errno %d - moznss error %d\n",
2334 tlsm_session_accept( tls_session *session )
2336 return tlsm_session_accept_or_connect( session, 1 );
2340 tlsm_session_connect( LDAP *ld, tls_session *session )
2342 return tlsm_session_accept_or_connect( session, 0 );
2346 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
2348 int prerror = PR_GetError();
2350 if ( ( prerror == PR_PENDING_INTERRUPT_ERROR ) || ( prerror == PR_WOULD_BLOCK_ERROR ) ) {
2351 tlsm_session *s = (tlsm_session *)session;
2352 struct tls_data *p = tlsm_get_pvt_tls_data( s );
2354 if ( p && ( p->io_flag == TLSM_READ ) ) {
2355 sb->sb_trans_needs_read = 1;
2357 } else if ( p && ( p->io_flag == TLSM_WRITE ) ) {
2358 sb->sb_trans_needs_write = 1;
2367 tlsm_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
2370 int prerror = PR_GetError();
2372 i = PR_GetErrorTextLength();
2374 char *msg = LDAP_MALLOC( i+1 );
2375 PR_GetErrorText( msg );
2376 memcpy( buf, msg, len );
2379 PR_GetErrorText( buf );
2380 } else if ( prerror ) {
2381 i = PR_snprintf( buf, len, "TLS error %d:%s",
2382 prerror, PR_ErrorToString( prerror, PR_LANGUAGE_I_DEFAULT ) );
2385 return ( i > 0 ) ? buf : NULL;
2389 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
2391 tlsm_session *s = (tlsm_session *)session;
2392 CERTCertificate *cert;
2394 cert = SSL_LocalCertificate( s );
2395 if (!cert) return LDAP_INVALID_CREDENTIALS;
2397 der_dn->bv_val = (char *)cert->derSubject.data;
2398 der_dn->bv_len = cert->derSubject.len;
2399 CERT_DestroyCertificate( cert );
2404 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
2406 tlsm_session *s = (tlsm_session *)session;
2407 CERTCertificate *cert;
2409 cert = SSL_PeerCertificate( s );
2410 if (!cert) return LDAP_INVALID_CREDENTIALS;
2412 der_dn->bv_val = (char *)cert->derSubject.data;
2413 der_dn->bv_len = cert->derSubject.len;
2414 CERT_DestroyCertificate( cert );
2418 /* what kind of hostname were we given? */
2424 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
2426 tlsm_session *s = (tlsm_session *)session;
2427 CERTCertificate *cert;
2428 const char *name, *domain = NULL, *ptr;
2429 int ret, ntype = IS_DNS, nlen, dlen;
2430 #ifdef LDAP_PF_INET6
2431 struct in6_addr addr;
2433 struct in_addr addr;
2438 if( ldap_int_hostname &&
2439 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
2441 name = ldap_int_hostname;
2445 nlen = strlen( name );
2447 cert = SSL_PeerCertificate( s );
2449 Debug( LDAP_DEBUG_ANY,
2450 "TLS: unable to get peer certificate.\n",
2452 /* if this was a fatal condition, things would have
2453 * aborted long before now.
2455 return LDAP_SUCCESS;
2458 #ifdef LDAP_PF_INET6
2459 if (name[0] == '[' && strchr(name, ']')) {
2460 char *n2 = ldap_strdup(name+1);
2461 *strchr(n2, ']') = 0;
2462 if (inet_pton(AF_INET6, n2, &addr))
2467 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
2468 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
2470 if (ntype == IS_DNS ) {
2471 domain = strchr( name, '.' );
2473 dlen = nlen - ( domain - name );
2476 ret = LDAP_LOCAL_ERROR;
2478 rv = CERT_FindCertExtension( cert, SEC_OID_X509_SUBJECT_ALT_NAME,
2480 if ( rv == SECSuccess && altname.data ) {
2482 CERTGeneralName *names, *cur;
2484 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
2486 ret = LDAP_NO_MEMORY;
2490 names = cur = CERT_DecodeAltNameExtension(arena, &altname);
2499 if ( !cur->name.other.len ) continue;
2501 host = (char *)cur->name.other.data;
2502 hlen = cur->name.other.len;
2504 if ( cur->type == certDNSName ) {
2505 if ( ntype != IS_DNS ) continue;
2507 /* is this an exact match? */
2508 if ( nlen == hlen && !strncasecmp( name, host, nlen )) {
2513 /* is this a wildcard match? */
2514 if ( domain && host[0] == '*' && host[1] == '.' &&
2515 dlen == hlen-1 && !strncasecmp( domain, host+1, dlen )) {
2519 } else if ( cur->type == certIPAddress ) {
2520 if ( ntype == IS_DNS ) continue;
2522 #ifdef LDAP_PF_INET6
2523 if (ntype == IS_IP6 && hlen != sizeof(struct in6_addr)) {
2527 if (ntype == IS_IP4 && hlen != sizeof(struct in_addr)) {
2530 if (!memcmp(host, &addr, hlen)) {
2535 } while (( cur = CERT_GetNextGeneralName( cur )) != names );
2537 PORT_FreeArena( arena, PR_FALSE );
2538 SECITEM_FreeItem( &altname, PR_FALSE );
2540 /* no altnames matched, try the CN */
2541 if ( ret != LDAP_SUCCESS ) {
2542 /* find the last CN */
2543 CERTRDN *rdn, **rdns;
2544 CERTAVA *lastava = NULL;
2548 rdns = cert->subject.rdns;
2549 while ( rdns && ( rdn = *rdns++ )) {
2550 CERTAVA *ava, **avas = rdn->avas;
2551 while ( avas && ( ava = *avas++ )) {
2552 if ( CERT_GetAVATag( ava ) == SEC_OID_AVA_COMMON_NAME )
2557 SECItem *av = CERT_DecodeAVAValue( &lastava->value );
2559 if ( av->len == nlen && !strncasecmp( name, (char *)av->data, nlen )) {
2561 } else if ( av->data[0] == '*' && av->data[1] == '.' &&
2562 domain && dlen == av->len - 1 && !strncasecmp( name,
2563 (char *)(av->data+1), dlen )) {
2567 if ( len >= sizeof(buf) )
2568 len = sizeof(buf)-1;
2569 memcpy( buf, av->data, len );
2572 SECITEM_FreeItem( av, PR_TRUE );
2575 if ( ret != LDAP_SUCCESS ) {
2576 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
2577 "common name in certificate (%s).\n",
2579 ret = LDAP_CONNECT_ERROR;
2580 if ( ld->ld_error ) {
2581 LDAP_FREE( ld->ld_error );
2583 ld->ld_error = LDAP_STRDUP(
2584 _("TLS: hostname does not match CN in peer certificate"));
2589 CERT_DestroyCertificate( cert );
2594 tlsm_session_strength( tls_session *session )
2596 tlsm_session *s = (tlsm_session *)session;
2599 rc = SSL_SecurityStatus( s, NULL, NULL, NULL, &keySize,
2601 return rc ? 0 : keySize;
2605 * TLS support for LBER Sockbufs
2608 static PRStatus PR_CALLBACK
2609 tlsm_PR_Close(PRFileDesc *fd)
2611 int rc = PR_SUCCESS;
2613 /* we don't need to actually close anything here, just
2614 pop our io layer off the stack */
2615 fd->secret = NULL; /* must have been freed before calling PR_Close */
2617 fd = PR_PopIOLayer( fd, tlsm_layer_id );
2618 /* if we are not the last layer, pass the close along */
2623 rc = fd->methods->close( fd );
2626 /* we are the last layer - just call our dtor */
2633 static PRStatus PR_CALLBACK
2634 tlsm_PR_Shutdown(PRFileDesc *fd, PRShutdownHow how)
2636 int rc = PR_SUCCESS;
2639 rc = PR_Shutdown( fd->lower, how );
2645 static int PR_CALLBACK
2646 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
2647 PRIntervalTime timeout)
2652 if ( buf == NULL || len <= 0 ) return 0;
2654 p = tlsm_get_pvt_tls_data( fd );
2656 if ( p == NULL || p->sbiod == NULL ) {
2660 rc = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
2662 tlsm_map_error( errno );
2663 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2664 p->nonblock = PR_TRUE; /* fd is using non-blocking io */
2665 } else if ( errno ) { /* real error */
2666 Debug( LDAP_DEBUG_TRACE,
2667 "TLS: error: tlsm_PR_Recv returned %d - error %d:%s\n",
2668 rc, errno, STRERROR(errno) );
2670 } else if ( ( rc > 0 ) && ( len > 0 ) && ( p->firsttag == LBER_DEFAULT ) ) {
2671 p->firsttag = (ber_tag_t)*((char *)buf);
2673 p->io_flag = TLSM_READ;
2678 static int PR_CALLBACK
2679 tlsm_PR_Send(PRFileDesc *fd, const 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_WRITE_NEXT( p->sbiod, (char *)buf, len );
2695 tlsm_map_error( errno );
2696 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2697 p->nonblock = PR_TRUE;
2698 } else if ( errno ) { /* real error */
2699 Debug( LDAP_DEBUG_TRACE,
2700 "TLS: error: tlsm_PR_Send returned %d - error %d:%s\n",
2701 rc, errno, STRERROR(errno) );
2704 p->io_flag = TLSM_WRITE;
2709 static int PR_CALLBACK
2710 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
2712 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2715 static int PR_CALLBACK
2716 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
2718 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2721 static PRStatus PR_CALLBACK
2722 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
2727 p = tlsm_get_pvt_tls_data( fd );
2729 if ( p == NULL || p->sbiod == NULL ) {
2732 len = sizeof(PRNetAddr);
2733 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
2736 static PRStatus PR_CALLBACK
2737 tlsm_PR_GetSocketOption(PRFileDesc *fd, PRSocketOptionData *data)
2740 p = tlsm_get_pvt_tls_data( fd );
2746 /* only the nonblocking option is supported at this time
2747 MozNSS SSL code needs it */
2748 if ( data->option != PR_SockOpt_Nonblocking ) {
2749 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2753 int flags = fcntl( p->sbiod->sbiod_sb->sb_fd, F_GETFL );
2754 data->value.non_blocking = (flags & O_NONBLOCK) ? PR_TRUE : PR_FALSE;
2756 data->value.non_blocking = p->nonblock;
2761 static PRStatus PR_CALLBACK
2764 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2768 static PRFileDesc * PR_CALLBACK
2771 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2775 static PRInt16 PR_CALLBACK
2778 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2782 static PRInt32 PR_CALLBACK
2785 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2789 static PRInt64 PR_CALLBACK
2794 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2799 static const PRIOMethods tlsm_PR_methods = {
2801 tlsm_PR_Close, /* close */
2802 tlsm_PR_Read, /* read */
2803 tlsm_PR_Write, /* write */
2804 tlsm_PR_i32_unimp, /* available */
2805 tlsm_PR_i64_unimp, /* available64 */
2806 tlsm_PR_prs_unimp, /* fsync */
2807 tlsm_PR_i32_unimp, /* seek */
2808 tlsm_PR_i64_unimp, /* seek64 */
2809 tlsm_PR_prs_unimp, /* fileInfo */
2810 tlsm_PR_prs_unimp, /* fileInfo64 */
2811 tlsm_PR_i32_unimp, /* writev */
2812 tlsm_PR_prs_unimp, /* connect */
2813 tlsm_PR_pfd_unimp, /* accept */
2814 tlsm_PR_prs_unimp, /* bind */
2815 tlsm_PR_prs_unimp, /* listen */
2816 (PRShutdownFN)tlsm_PR_Shutdown, /* shutdown */
2817 tlsm_PR_Recv, /* recv */
2818 tlsm_PR_Send, /* send */
2819 tlsm_PR_i32_unimp, /* recvfrom */
2820 tlsm_PR_i32_unimp, /* sendto */
2821 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
2822 tlsm_PR_i32_unimp, /* acceptread */
2823 tlsm_PR_i32_unimp, /* transmitfile */
2824 tlsm_PR_prs_unimp, /* getsockname */
2825 tlsm_PR_GetPeerName, /* getpeername */
2826 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
2827 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
2828 tlsm_PR_GetSocketOption, /* getsocketoption */
2829 tlsm_PR_i32_unimp, /* setsocketoption */
2830 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
2831 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
2832 tlsm_PR_i32_unimp, /* reserved for future use */
2833 tlsm_PR_i32_unimp, /* reserved for future use */
2834 tlsm_PR_i32_unimp, /* reserved for future use */
2835 tlsm_PR_i32_unimp /* reserved for future use */
2839 * Initialize TLS subsystem. Should be called only once.
2840 * See tlsm_deferred_init for the bulk of the init process
2847 tlsm_layer_id = PR_GetUniqueIdentity( "OpenLDAP" );
2853 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
2856 tlsm_session *session = arg;
2859 assert( sbiod != NULL );
2861 p = LBER_MALLOC( sizeof( *p ) );
2866 fd = PR_GetIdentitiesLayer( session, tlsm_layer_id );
2872 fd->secret = (PRFilePrivate *)p;
2873 p->session = session;
2875 p->firsttag = LBER_DEFAULT;
2876 sbiod->sbiod_pvt = p;
2881 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
2885 assert( sbiod != NULL );
2886 assert( sbiod->sbiod_pvt != NULL );
2888 p = (struct tls_data *)sbiod->sbiod_pvt;
2889 PR_Close( p->session );
2890 LBER_FREE( sbiod->sbiod_pvt );
2891 sbiod->sbiod_pvt = NULL;
2896 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
2900 assert( sbiod != NULL );
2901 assert( sbiod->sbiod_pvt != NULL );
2903 p = (struct tls_data *)sbiod->sbiod_pvt;
2904 PR_Shutdown( p->session, PR_SHUTDOWN_BOTH );
2909 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
2913 assert( sbiod != NULL );
2914 assert( sbiod->sbiod_pvt != NULL );
2916 p = (struct tls_data *)sbiod->sbiod_pvt;
2918 if ( opt == LBER_SB_OPT_GET_SSL ) {
2919 *((tlsm_session **)arg) = p->session;
2922 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
2923 if ( p && ( SSL_DataPending( p->session ) > 0 ) ) {
2929 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
2933 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2939 assert( sbiod != NULL );
2940 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2942 p = (struct tls_data *)sbiod->sbiod_pvt;
2944 ret = PR_Recv( p->session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2946 err = PR_GetError();
2947 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2948 sbiod->sbiod_sb->sb_trans_needs_read = 1;
2949 sock_errset(EWOULDBLOCK);
2952 sbiod->sbiod_sb->sb_trans_needs_read = 0;
2958 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2964 assert( sbiod != NULL );
2965 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2967 p = (struct tls_data *)sbiod->sbiod_pvt;
2969 ret = PR_Send( p->session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2971 err = PR_GetError();
2972 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2973 sbiod->sbiod_sb->sb_trans_needs_write = 1;
2974 sock_errset(EWOULDBLOCK);
2978 sbiod->sbiod_sb->sb_trans_needs_write = 0;
2983 static Sockbuf_IO tlsm_sbio =
2985 tlsm_sb_setup, /* sbi_setup */
2986 tlsm_sb_remove, /* sbi_remove */
2987 tlsm_sb_ctrl, /* sbi_ctrl */
2988 tlsm_sb_read, /* sbi_read */
2989 tlsm_sb_write, /* sbi_write */
2990 tlsm_sb_close /* sbi_close */
2993 tls_impl ldap_int_tls_impl = {
3005 tlsm_session_connect,
3006 tlsm_session_accept,
3007 tlsm_session_upflags,
3008 tlsm_session_errmsg,
3010 tlsm_session_peer_dn,
3011 tlsm_session_chkhost,
3012 tlsm_session_strength,
3016 #ifdef LDAP_R_COMPILE
3025 #endif /* HAVE_MOZNSS */