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-2009 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 */
57 #include <private/pprio.h>
65 typedef struct tlsm_ctx {
68 PRBool tc_verify_cert;
69 CERTCertDBHandle *tc_certdb;
72 struct ldaptls *tc_config;
75 PRCallOnceType tc_callonce;
77 ldap_pvt_thread_mutex_t tc_refmutex;
81 typedef PRFileDesc tlsm_session;
83 static PRDescIdentity tlsm_layer_id;
85 static const PRIOMethods tlsm_PR_methods;
87 static int tlsm_did_init;
89 #define DEFAULT_TOKEN_NAME "default"
91 /* forward declaration */
92 static int tlsm_init( void );
101 #endif /* LDAP_R_COMPILE */
104 tlsm_dump_cipher_info(PRFileDesc *fd)
108 for (ii = 0; ii < SSL_NumImplementedCiphers; ++ii) {
109 PRInt32 cipher = (PRInt32)SSL_ImplementedCiphers[ii];
110 PRBool enabled = PR_FALSE;
112 SSLCipherSuiteInfo info;
115 SSL_CipherPrefGet(fd, cipher, &enabled);
117 SSL_CipherPrefGetDefault(cipher, &enabled);
119 SSL_CipherPolicyGet(cipher, &policy);
120 SSL_GetCipherSuiteInfo(cipher, &info, (PRUintn)sizeof(info));
121 Debug( LDAP_DEBUG_TRACE,
122 "TLS: cipher: %d - %s, enabled: %d, ",
123 info.cipherSuite, info.cipherSuiteName, enabled );
124 Debug( LDAP_DEBUG_TRACE,
125 "policy: %d\n", policy, 0, 0 );
131 /* Cipher definitions */
133 char *ossl_name; /* The OpenSSL cipher name */
134 int num; /* The cipher id */
135 int attr; /* cipher attributes: algorithms, etc */
136 int version; /* protocol version valid for this cipher */
137 int bits; /* bits of strength */
138 int alg_bits; /* bits of the algorithm */
139 int strength; /* LOW, MEDIUM, HIGH */
140 int enabled; /* Enabled by default? */
143 /* cipher attributes */
144 #define SSL_kRSA 0x00000001L
145 #define SSL_aRSA 0x00000002L
146 #define SSL_aDSS 0x00000004L
147 #define SSL_DSS SSL_aDSS
148 #define SSL_eNULL 0x00000008L
149 #define SSL_DES 0x00000010L
150 #define SSL_3DES 0x00000020L
151 #define SSL_RC4 0x00000040L
152 #define SSL_RC2 0x00000080L
153 #define SSL_AES 0x00000100L
154 #define SSL_MD5 0x00000200L
155 #define SSL_SHA1 0x00000400L
156 #define SSL_SHA SSL_SHA1
157 #define SSL_RSA (SSL_kRSA|SSL_aRSA)
159 /* cipher strength */
160 #define SSL_NULL 0x00000001L
161 #define SSL_EXPORT40 0x00000002L
162 #define SSL_EXPORT56 0x00000004L
163 #define SSL_LOW 0x00000008L
164 #define SSL_MEDIUM 0x00000010L
165 #define SSL_HIGH 0x00000020L
167 #define SSL2 0x00000001L
168 #define SSL3 0x00000002L
169 /* OpenSSL treats SSL3 and TLSv1 the same */
172 /* Cipher translation */
173 static cipher_properties ciphers_def[] = {
175 {"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},
176 {"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},
177 {"RC4-MD5", SSL_EN_RC4_128_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
178 {"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},
179 {"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},
180 {"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},
183 {"RC4-MD5", SSL_RSA_WITH_RC4_128_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
184 {"RC4-SHA", SSL_RSA_WITH_RC4_128_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA1, SSL3, 128, 128, SSL_MEDIUM, SSL_NOT_ALLOWED},
185 {"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},
186 {"DES-CBC-SHA", SSL_RSA_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA1, SSL3, 56, 56, SSL_LOW, SSL_ALLOWED},
187 {"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},
188 {"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},
189 {"NULL-MD5", SSL_RSA_WITH_NULL_MD5, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_MD5, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
190 {"NULL-SHA", SSL_RSA_WITH_NULL_SHA, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_SHA1, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
193 {"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},
194 {"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},
195 {"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},
196 {"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},
199 #define ciphernum (sizeof(ciphers_def)/sizeof(cipher_properties))
201 /* given err which is the current errno, calls PR_SetError with
202 the corresponding NSPR error code */
204 tlsm_map_error(int err)
210 prError = PR_NO_ACCESS_RIGHTS_ERROR;
213 prError = PR_ADDRESS_IN_USE_ERROR;
216 prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
219 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
222 prError = PR_WOULD_BLOCK_ERROR;
225 * On QNX and Neutrino, EALREADY is defined as EBUSY.
227 #if EALREADY != EBUSY
229 prError = PR_ALREADY_INITIATED_ERROR;
233 prError = PR_BAD_DESCRIPTOR_ERROR;
237 prError = PR_IO_ERROR;
241 prError = PR_FILESYSTEM_MOUNTED_ERROR;
244 prError = PR_CONNECT_ABORTED_ERROR;
247 prError = PR_CONNECT_REFUSED_ERROR;
250 prError = PR_CONNECT_RESET_ERROR;
253 prError = PR_DEADLOCK_ERROR;
257 prError = PR_DIRECTORY_CORRUPTED_ERROR;
262 prError = PR_NO_DEVICE_SPACE_ERROR;
266 prError = PR_FILE_EXISTS_ERROR;
269 prError = PR_ACCESS_FAULT_ERROR;
272 prError = PR_FILE_TOO_BIG_ERROR;
275 prError = PR_HOST_UNREACHABLE_ERROR;
278 prError = PR_IN_PROGRESS_ERROR;
281 prError = PR_PENDING_INTERRUPT_ERROR;
284 prError = PR_INVALID_ARGUMENT_ERROR;
287 prError = PR_IO_ERROR;
290 prError = PR_IS_CONNECTED_ERROR;
293 prError = PR_IS_DIRECTORY_ERROR;
296 prError = PR_LOOP_ERROR;
299 prError = PR_PROC_DESC_TABLE_FULL_ERROR;
302 prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
305 prError = PR_INVALID_ARGUMENT_ERROR;
309 prError = PR_REMOTE_FILE_ERROR;
313 prError = PR_NAME_TOO_LONG_ERROR;
316 prError = PR_NETWORK_UNREACHABLE_ERROR;
319 prError = PR_SYS_DESC_TABLE_FULL_ERROR;
322 * On SCO OpenServer 5, ENOBUFS is defined as ENOSR.
324 #if defined(ENOBUFS) && (ENOBUFS != ENOSR)
326 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
330 prError = PR_FILE_NOT_FOUND_ERROR;
333 prError = PR_FILE_NOT_FOUND_ERROR;
336 prError = PR_FILE_IS_LOCKED_ERROR;
340 prError = PR_REMOTE_FILE_ERROR;
344 prError = PR_OUT_OF_MEMORY_ERROR;
347 prError = PR_INVALID_ARGUMENT_ERROR;
350 prError = PR_NO_DEVICE_SPACE_ERROR;
354 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
358 prError = PR_NOT_CONNECTED_ERROR;
361 prError = PR_NOT_DIRECTORY_ERROR;
364 prError = PR_NOT_SOCKET_ERROR;
367 prError = PR_FILE_NOT_FOUND_ERROR;
370 prError = PR_NOT_TCP_SOCKET_ERROR;
374 prError = PR_BUFFER_OVERFLOW_ERROR;
378 prError = PR_NO_ACCESS_RIGHTS_ERROR;
381 prError = PR_CONNECT_RESET_ERROR;
385 prError = PR_IO_ERROR;
388 case EPROTONOSUPPORT:
389 prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
392 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
395 prError = PR_INVALID_METHOD_ERROR;
398 prError = PR_READ_ONLY_FILESYSTEM_ERROR;
401 prError = PR_INVALID_METHOD_ERROR;
404 prError = PR_IO_TIMEOUT_ERROR;
406 #if EWOULDBLOCK != EAGAIN
408 prError = PR_WOULD_BLOCK_ERROR;
412 prError = PR_NOT_SAME_DEVICE_ERROR;
415 prError = PR_UNKNOWN_ERROR;
418 PR_SetError( prError, err );
422 * cipher_list is an integer array with the following values:
423 * -1: never enable this cipher
428 nss_parse_ciphers(const char *cipherstr, int cipher_list[ciphernum])
437 /* All disabled to start */
438 for (i=0; i<ciphernum; i++)
441 ciphertip = strdup(cipherstr);
442 cipher = ciphers = ciphertip;
444 while (ciphers && (strlen(ciphers))) {
445 while ((*cipher) && (isspace(*cipher)))
450 case '+': /* Add something */
454 case '-': /* Subtract something */
458 case '!': /* Disable something */
467 if ((ciphers = strchr(cipher, ':'))) {
471 /* Do the easy one first */
472 if (!strcmp(cipher, "ALL")) {
473 for (i=0; i<ciphernum; i++) {
474 if (!(ciphers_def[i].attr & SSL_eNULL))
475 cipher_list[i] = action;
477 } else if (!strcmp(cipher, "COMPLEMENTOFALL")) {
478 for (i=0; i<ciphernum; i++) {
479 if ((ciphers_def[i].attr & SSL_eNULL))
480 cipher_list[i] = action;
482 } else if (!strcmp(cipher, "DEFAULT")) {
483 for (i=0; i<ciphernum; i++) {
484 cipher_list[i] = ciphers_def[i].enabled == SSL_ALLOWED ? 1 : 0;
493 while (c && (strlen(c))) {
495 if ((c = strchr(cipher, '+'))) {
499 if (!strcmp(cipher, "RSA")) {
501 } else if ((!strcmp(cipher, "NULL")) || (!strcmp(cipher, "eNULL"))) {
503 } else if (!strcmp(cipher, "AES")) {
505 } else if (!strcmp(cipher, "3DES")) {
507 } else if (!strcmp(cipher, "DES")) {
509 } else if (!strcmp(cipher, "RC4")) {
511 } else if (!strcmp(cipher, "RC2")) {
513 } else if (!strcmp(cipher, "MD5")) {
515 } else if ((!strcmp(cipher, "SHA")) || (!strcmp(cipher, "SHA1"))) {
517 } else if (!strcmp(cipher, "SSLv2")) {
519 } else if (!strcmp(cipher, "SSLv3")) {
521 } else if (!strcmp(cipher, "TLSv1")) {
523 } else if (!strcmp(cipher, "HIGH")) {
524 strength |= SSL_HIGH;
525 } else if (!strcmp(cipher, "MEDIUM")) {
526 strength |= SSL_MEDIUM;
527 } else if (!strcmp(cipher, "LOW")) {
529 } else if ((!strcmp(cipher, "EXPORT")) || (!strcmp(cipher, "EXP"))) {
530 strength |= SSL_EXPORT40|SSL_EXPORT56;
531 } else if (!strcmp(cipher, "EXPORT40")) {
532 strength |= SSL_EXPORT40;
533 } else if (!strcmp(cipher, "EXPORT56")) {
534 strength |= SSL_EXPORT56;
542 /* If we have a mask, apply it. If not then perhaps they provided
543 * a specific cipher to enable.
545 if (mask || strength || protocol) {
546 for (i=0; i<ciphernum; i++) {
547 if (((ciphers_def[i].attr & mask) ||
548 (ciphers_def[i].strength & strength) ||
549 (ciphers_def[i].version & protocol)) &&
550 (cipher_list[i] != -1)) {
551 /* Enable the NULL ciphers only if explicity
553 if (ciphers_def[i].attr & SSL_eNULL) {
554 if (mask & SSL_eNULL)
555 cipher_list[i] = action;
557 cipher_list[i] = action;
561 for (i=0; i<ciphernum; i++) {
562 if (!strcmp(ciphers_def[i].ossl_name, cipher) &&
563 cipher_list[1] != -1)
564 cipher_list[i] = action;
573 /* See if any ciphers were enabled */
575 for (i=0; i<ciphernum; i++) {
576 if (cipher_list[i] == 1)
586 tlsm_parse_ciphers(tlsm_ctx *ctx, const char *str)
588 int cipher_state[ciphernum];
594 rv = nss_parse_ciphers(str, cipher_state);
597 /* First disable everything */
598 for (i = 0; i < SSL_NumImplementedCiphers; i++)
599 SSL_CipherPrefSet(ctx->tc_model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
601 /* Now enable what was requested */
602 for (i=0; i<ciphernum; i++) {
603 SSLCipherSuiteInfo suite;
606 if (SSL_GetCipherSuiteInfo(ciphers_def[i].num, &suite, sizeof suite)
608 enabled = cipher_state[i] < 0 ? 0 : cipher_state[i];
609 if (enabled == SSL_ALLOWED) {
610 if (PK11_IsFIPS() && !suite.isFIPS)
611 enabled = SSL_NOT_ALLOWED;
613 SSL_CipherPrefSet(ctx->tc_model, ciphers_def[i].num, enabled);
618 return rv == 1 ? 0 : -1;
622 tlsm_bad_cert_handler(void *arg, PRFileDesc *ssl)
624 SECStatus success = SECSuccess;
626 tlsm_ctx *ctx = (tlsm_ctx *)arg;
632 err = PORT_GetError();
635 case SEC_ERROR_UNTRUSTED_ISSUER:
636 case SEC_ERROR_UNKNOWN_ISSUER:
637 case SEC_ERROR_EXPIRED_CERTIFICATE:
638 if (ctx->tc_verify_cert) {
639 success = SECFailure;
643 success = SECFailure;
651 tlsm_dump_security_status(PRFileDesc *fd)
653 char * cp; /* bulk cipher name */
654 char * ip; /* cert issuer DN */
655 char * sp; /* cert subject DN */
656 int op; /* High, Low, Off */
657 int kp0; /* total key bits */
658 int kp1; /* secret key bits */
659 SSL3Statistics * ssl3stats = SSL_GetStatistics();
661 SSL_SecurityStatus( fd, &op, &cp, &kp0, &kp1, &ip, &sp );
662 Debug( LDAP_DEBUG_TRACE,
663 "TLS certificate verification: subject: %s, issuer: %s, cipher: %s, ",
664 sp ? sp : "-unknown-", ip ? ip : "-unknown-", cp ? cp : "-unknown-" );
668 Debug( LDAP_DEBUG_TRACE,
669 "security level: %s, secret key bits: %d, total key bits: %d, ",
670 ((op == SSL_SECURITY_STATUS_ON_HIGH) ? "high" :
671 ((op == SSL_SECURITY_STATUS_ON_LOW) ? "low" : "off")),
674 Debug( LDAP_DEBUG_TRACE,
675 "cache hits: %ld, cache misses: %ld, cache not reusable: %ld\n",
676 ssl3stats->hch_sid_cache_hits, ssl3stats->hch_sid_cache_misses,
677 ssl3stats->hch_sid_cache_not_ok );
683 tlsm_auth_cert_handler(void *arg, PRFileDesc *fd,
684 PRBool checksig, PRBool isServer)
686 SECStatus ret = SSL_AuthCertificate(arg, fd, checksig, isServer);
688 Debug( LDAP_DEBUG_TRACE,
689 "TLS certificate verification: %s: %s,",
690 ret == SECSuccess ? "ok" : "bad",
691 tlsm_dump_security_status( fd ), 0 );
693 if ( ret != SECSuccess ) {
694 PRErrorCode errcode = PORT_GetError();
695 Debug( LDAP_DEBUG_ANY,
696 "TLS certificate verification: Error, %d: %s\n",
697 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 ) ;
704 tlsm_dirname(const char *pathname)
708 char sep = PR_GetDirectorySeparator();
710 if (pathname && (p = PL_strrchr(pathname, sep)) && (p > pathname)) {
711 ret = PL_strndup(pathname, (p - pathname));
718 * This is the part of the init we defer until we get the
719 * actual security configuration information. This is
720 * only called once, protected by a PRCallOnce
721 * NOTE: This must be done before the first call to SSL_ImportFD,
722 * especially the setting of the policy
723 * NOTE: This must be called after fork()
726 tlsm_deferred_init( void *arg )
728 tlsm_ctx *ctx = (tlsm_ctx *)arg;
729 struct ldaptls *lt = ctx->tc_config;
730 char *securitydir = NULL;
735 /* NSS support for multi-init is coming */
736 #ifndef NSS_MULTI_INIT
737 if ( !NSS_IsInitialized() ) {
738 #endif /* NSS_MULTI_INIT */
740 MOZNSS_DIR will override everything else - you can
741 always set MOZNSS_DIR to force the use of this
743 DEFAULT_MOZNSS_DIR will only be used if the code cannot
744 find a security dir to use based on the current
747 if ( (val = PR_GetEnv( "MOZNSS_DIR" ) ) && (*val) ) {
748 securitydir = PL_strdup( val );
750 } else if ( lt->lt_cacertdir ) {
751 securitydir = lt->lt_cacertdir;
752 } else if ( lt->lt_cacertfile ) {
753 securitydir = tlsm_dirname( lt->lt_cacertfile );
755 } else if ( lt->lt_certfile ) {
756 securitydir = tlsm_dirname( lt->lt_certfile );
758 } else if ( lt->lt_keyfile ) {
759 securitydir = tlsm_dirname( lt->lt_keyfile );
761 } else if ( (val = PR_GetEnv( "DEFAULT_MOZNSS_DIR" ) ) && (*val) ) {
762 securitydir = PL_strdup( val );
765 securitydir = "/etc/pki/nssdb";
768 if ( NSS_Initialize( securitydir, "", "", SECMOD_DB, NSS_INIT_READONLY ) ) {
769 errcode = PORT_GetError();
770 Debug( LDAP_DEBUG_ANY,
771 "TLS: could not initialize moznss using security dir %s - error %d:%s.\n",
772 securitydir, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
774 PL_strfree( securitydir );
780 PL_strfree( securitydir );
783 NSS_SetDomesticPolicy();
784 tlsm_did_init = 1; /* we did the init - we should also clean up */
785 #ifndef NSS_MULTI_INIT
787 #endif /* NSS_MULTI_INIT */
792 #ifdef READ_PASSWORD_FROM_FILE
794 tlsm_get_pin_from_file(const char *token_name, tlsm_ctx *ctx)
797 char *contents = NULL;
800 char *candidate = NULL;
801 PRFileInfo file_info;
802 PRFileDesc *pwd_fileptr = PR_Open( ctx->tc_pin_file, PR_RDONLY, 00400 );
804 /* open the password file */
805 if ( !pwd_fileptr ) {
806 PRErrorCode errcode = PR_GetError();
807 Debug( LDAP_DEBUG_ANY,
808 "TLS: could not open security pin file %s - error %d:%s.\n",
809 ctx->tc_pin_file, errcode,
810 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
814 /* get the file size */
815 if ( PR_SUCCESS != PR_GetFileInfo( ctx->tc_pin_file, &file_info ) ) {
816 PRErrorCode errcode = PR_GetError();
817 Debug( LDAP_DEBUG_ANY,
818 "TLS: could not get file info from pin file %s - error %d:%s.\n",
819 ctx->tc_pin_file, errcode,
820 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
824 /* create a buffer to hold the file contents */
825 if ( !( contents = PR_MALLOC( file_info.size + 1 ) ) ) {
826 PRErrorCode errcode = PR_GetError();
827 Debug( LDAP_DEBUG_ANY,
828 "TLS: could not alloc a buffer for contents of pin file %s - error %d:%s.\n",
829 ctx->tc_pin_file, errcode,
830 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
834 /* read file into the buffer */
835 if( PR_Read( pwd_fileptr, contents, file_info.size ) <= 0 ) {
836 PRErrorCode errcode = PR_GetError();
837 Debug( LDAP_DEBUG_ANY,
838 "TLS: could not read the file contents from pin file %s - error %d:%s.\n",
839 ctx->tc_pin_file, errcode,
840 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
844 /* format is [tokenname:]password EOL [tokenname:]password EOL ... */
845 /* if you want to use a password containing a colon character, use
846 the special tokenname "default" */
847 for ( line = PL_strtok_r( contents, "\r\n", &lasts ); line;
848 line = PL_strtok_r( NULL, "\r\n", &lasts ) ) {
852 continue; /* skip blank lines */
854 colon = PL_strchr( line, ':' );
856 if ( *(colon + 1) && token_name &&
857 !PL_strncmp( token_name, line, colon-line ) ) {
858 candidate = colon + 1; /* found a definite match */
860 } else if ( !PL_strncmp( DEFAULT_TOKEN_NAME, line, colon-line ) ) {
861 candidate = colon + 1; /* found possible match */
863 } else { /* no token name */
869 PR_Close( pwd_fileptr );
872 pwdstr = PL_strdup( candidate );
874 PL_strfree( contents );
878 #endif /* READ_PASSWORD_FROM_FILE */
880 #ifdef READ_PASSWORD_FROM_STDIN
882 * Turn the echoing off on a tty.
887 if ( isatty( fd ) ) {
889 tcgetattr( fd, &tio );
890 tio.c_lflag &= ~ECHO;
891 tcsetattr( fd, TCSAFLUSH, &tio );
896 * Turn the echoing on on a tty.
901 if ( isatty( fd ) ) {
903 tcgetattr( fd, &tio );
905 tcsetattr( fd, TCSAFLUSH, &tio );
906 tcsetattr( fd, TCSAFLUSH, &tio );
909 #endif /* READ_PASSWORD_FROM_STDIN */
912 * This does the actual work of reading the pin/password/pass phrase
915 tlsm_get_pin(PK11SlotInfo *slot, PRBool retry, tlsm_ctx *ctx)
917 char *token_name = NULL;
920 token_name = PK11_GetTokenName( slot );
921 #ifdef READ_PASSWORD_FROM_FILE
922 /* Try to get the passwords from the password file if it exists.
923 * THIS IS UNSAFE and is provided for convenience only. Without this
924 * capability the server would have to be started in foreground mode
925 * if using an encrypted key.
927 if ( ctx->tc_pin_file ) {
928 pwdstr = tlsm_get_pin_from_file( token_name, ctx );
930 #endif /* RETRIEVE_PASSWORD_FROM_FILE */
931 #ifdef READ_PASSWORD_FROM_STDIN
933 int infd = PR_FileDesc2NativeHandle( PR_STDIN );
934 int isTTY = isatty( infd );
935 unsigned char phrase[200];
936 /* Prompt for password */
939 "Please enter pin, password, or pass phrase for security token '%s': ",
940 token_name ? token_name : DEFAULT_TOKEN_NAME );
943 fgets( (char*)phrase, sizeof(phrase), stdin );
945 fprintf( stdout, "\n" );
948 /* stomp on newline */
949 phrase[strlen((char*)phrase)-1] = 0;
951 pwdstr = PL_strdup( (char*)phrase );
954 #endif /* READ_PASSWORD_FROM_STDIN */
959 * PKCS11 devices (including the internal softokn cert/key database)
960 * may be protected by a pin or password or even pass phrase
961 * MozNSS needs a way for the user to provide that
964 tlsm_pin_prompt(PK11SlotInfo *slot, PRBool retry, void *arg)
966 tlsm_ctx *ctx = (tlsm_ctx *)arg;
968 return tlsm_get_pin( slot, retry, ctx );
972 tlsm_authenticate( tlsm_ctx *ctx, const char *certname, const char *pininfo )
974 const char *colon = NULL;
975 char *token_name = NULL;
976 PK11SlotInfo *slot = NULL;
979 if ( !certname || !*certname ) {
983 PK11_SetPasswordFunc( tlsm_pin_prompt );
985 if ( ( colon = PL_strchr( certname, ':' ) ) ) {
986 token_name = PL_strndup( certname, colon-certname );
990 slot = PK11_FindSlotByName( token_name );
992 slot = PK11_GetInternalKeySlot();
996 PRErrorCode errcode = PR_GetError();
997 Debug( LDAP_DEBUG_ANY,
998 "TLS: could not find the slot for security token %s - error %d:%s.\n",
999 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1000 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1005 PL_strfree( ctx->tc_pin_file );
1006 ctx->tc_pin_file = PL_strdup( pininfo );
1009 if ( PK11_NeedLogin( slot ) &&
1010 ( SECSuccess != PK11_Authenticate( slot, PR_FALSE, ctx ) ) ) {
1011 PRErrorCode errcode = PR_GetError();
1012 Debug( LDAP_DEBUG_ANY,
1013 "TLS: could not authenticate to the security token %s - error %d:%s.\n",
1014 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1015 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1018 rc = 0; /* success */
1022 PL_strfree( token_name );
1024 PK11_FreeSlot( slot );
1031 * Find and verify the certificate.
1032 * Either fd is given, in which case the cert will be taken from it via SSL_PeerCertificate
1033 * or certname is given, and it will be searched for by name
1036 tlsm_find_and_verify_cert_key(tlsm_ctx *ctx, PRFileDesc *fd, const char *certname, int isServer, CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey)
1038 CERTCertificate *cert = NULL;
1040 void *pin_arg = NULL;
1041 SECKEYPrivateKey *key = NULL;
1043 pin_arg = SSL_RevealPinArg( fd );
1045 cert = PK11_FindCertFromNickname( certname, pin_arg );
1047 PRErrorCode errcode = PR_GetError();
1048 Debug( LDAP_DEBUG_ANY,
1049 "TLS: error: the certificate %s could not be found in the database - error %d:%s\n",
1050 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1054 /* we are verifying the peer cert
1055 we also need to swap the isServer meaning */
1056 cert = SSL_PeerCertificate( fd );
1058 PRErrorCode errcode = PR_GetError();
1059 Debug( LDAP_DEBUG_ANY,
1060 "TLS: error: could not get the certificate from the peer connection - error %d:%s\n",
1061 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), NULL );
1064 isServer = !isServer; /* verify the peer's cert instead */
1067 key = PK11_FindKeyByAnyCert( cert, pin_arg );
1069 SECCertificateUsage certUsage;
1070 PRBool checkSig = PR_TRUE;
1074 *pRetKey = key; /* caller will deal with this */
1076 SECKEY_DestroyPrivateKey( key );
1079 certUsage = certificateUsageSSLServer;
1081 certUsage = certificateUsageSSLClient;
1083 if ( ctx->tc_verify_cert ) {
1086 checkSig = PR_FALSE;
1088 status = CERT_VerifyCertificateNow( ctx->tc_certdb, cert,
1089 checkSig, certUsage,
1091 if (status != SECSuccess) {
1092 PRErrorCode errcode = PR_GetError();
1093 Debug( LDAP_DEBUG_ANY,
1094 "TLS: error: the certificate %s is not valid - error %d:%s\n",
1095 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1097 rc = 0; /* success */
1100 PRErrorCode errcode = PR_GetError();
1101 Debug( LDAP_DEBUG_ANY,
1102 "TLS: error: could not find the private key for certificate %s - error %d:%s\n",
1103 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1107 *pRetCert = cert; /* caller will deal with this */
1109 CERT_DestroyCertificate( cert );
1116 tlsm_get_client_auth_data( void *arg, PRFileDesc *fd,
1117 CERTDistNames *caNames, CERTCertificate **pRetCert,
1118 SECKEYPrivateKey **pRetKey )
1120 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1123 /* don't need caNames - this function will call CERT_VerifyCertificateNow
1124 which will verify the cert against the known CAs */
1125 rc = tlsm_find_and_verify_cert_key( ctx, fd, ctx->tc_certname, 0, pRetCert, pRetKey );
1127 Debug( LDAP_DEBUG_ANY,
1128 "TLS: error: unable to perform client certificate authentication for "
1129 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1137 * ctx must have a tc_model that is valid
1138 * certname is in the form [<tokenname>:]<certnickname>
1139 * where <tokenname> is the name of the PKCS11 token
1140 * and <certnickname> is the nickname of the cert/key in
1144 tlsm_clientauth_init( tlsm_ctx *ctx, const char *certname )
1146 SECStatus status = SECFailure;
1149 PL_strfree( ctx->tc_certname );
1150 rc = tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, certname, 0, NULL, NULL );
1152 Debug( LDAP_DEBUG_ANY,
1153 "TLS: error: unable to set up client certificate authentication for "
1154 "certificate named %s\n", certname, 0, 0 );
1158 ctx->tc_certname = PL_strdup( certname );
1160 status = SSL_GetClientAuthDataHook( ctx->tc_model,
1161 tlsm_get_client_auth_data,
1164 return ( status == SECSuccess ? 0 : -1 );
1168 * Tear down the TLS subsystem. Should only be called once.
1171 tlsm_destroy( void )
1173 /* Only if we did the actual initialization */
1174 if ( tlsm_did_init ) {
1177 SSL_ShutdownServerSessionIDCache();
1178 SSL_ClearSessionCache();
1186 tlsm_ctx_new ( struct ldapoptions *lo )
1190 ctx = LDAP_MALLOC( sizeof (*ctx) );
1193 #ifdef LDAP_R_COMPILE
1194 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
1196 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 */
1197 ctx->tc_certdb = NULL;
1198 ctx->tc_certname = NULL;
1199 ctx->tc_pin_file = NULL;
1200 ctx->tc_model = NULL;
1201 memset(&ctx->tc_callonce, 0, sizeof(ctx->tc_callonce));
1202 ctx->tc_require_cert = lo->ldo_tls_require_cert;
1207 return (tls_ctx *)ctx;
1211 tlsm_ctx_ref( tls_ctx *ctx )
1213 tlsm_ctx *c = (tlsm_ctx *)ctx;
1214 #ifdef LDAP_R_COMPILE
1215 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
1218 #ifdef LDAP_R_COMPILE
1219 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
1224 tlsm_ctx_free ( tls_ctx *ctx )
1226 tlsm_ctx *c = (tlsm_ctx *)ctx;
1231 #ifdef LDAP_R_COMPILE
1232 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
1234 refcount = --c->tc_refcnt;
1235 #ifdef LDAP_R_COMPILE
1236 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
1240 PR_Close( c->tc_model );
1241 c->tc_certdb = NULL; /* if not the default, may have to clean up */
1242 PL_strfree( c->tc_certname );
1243 c->tc_certname = NULL;
1244 PL_strfree( c->tc_pin_file );
1245 c->tc_pin_file = NULL;
1246 #ifdef LDAP_R_COMPILE
1247 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
1253 * initialize a new TLS context
1256 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
1258 tlsm_ctx *ctx = (tlsm_ctx *)lo->ldo_tls_ctx;
1259 ctx->tc_is_server = is_server;
1265 tlsm_deferred_ctx_init( void *arg )
1267 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1268 PRBool sslv2 = PR_FALSE;
1269 PRBool sslv3 = PR_TRUE;
1270 PRBool tlsv1 = PR_TRUE;
1271 PRBool request_cert = PR_FALSE;
1272 PRInt32 require_cert = PR_FALSE;
1276 if ( tlsm_deferred_init( ctx ) ) {
1277 Debug( LDAP_DEBUG_ANY,
1278 "TLS: could perform TLS system initialization.\n",
1283 ctx->tc_certdb = CERT_GetDefaultCertDB(); /* replace with multi-init db call */
1285 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
1287 ctx->tc_model = SSL_ImportFD( NULL, fd );
1290 if ( !ctx->tc_model ) {
1291 PRErrorCode err = PR_GetError();
1292 Debug( LDAP_DEBUG_ANY,
1293 "TLS: could perform TLS socket I/O layer initialization - error %d:%s.\n",
1294 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1302 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE ) ) {
1303 Debug( LDAP_DEBUG_ANY,
1304 "TLS: could not set secure mode on.\n",
1309 lt = ctx->tc_config;
1311 /* default is sslv3 and tlsv1 */
1312 if ( lt->lt_protocol_min ) {
1313 if ( lt->lt_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 ) {
1315 } else if ( lt->lt_protocol_min <= LDAP_OPT_X_TLS_PROTOCOL_SSL2 ) {
1317 Debug( LDAP_DEBUG_ANY,
1318 "TLS: warning: minimum TLS protocol level set to "
1319 "include SSLv2 - SSLv2 is insecure - do not use\n", 0, 0, 0 );
1322 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL2, sslv2 ) ) {
1323 Debug( LDAP_DEBUG_ANY,
1324 "TLS: could not set SSLv2 mode on.\n",
1328 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL3, sslv3 ) ) {
1329 Debug( LDAP_DEBUG_ANY,
1330 "TLS: could not set SSLv3 mode on.\n",
1334 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_TLS, tlsv1 ) ) {
1335 Debug( LDAP_DEBUG_ANY,
1336 "TLS: could not set TLSv1 mode on.\n",
1341 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !ctx->tc_is_server ) ) {
1342 Debug( LDAP_DEBUG_ANY,
1343 "TLS: could not set handshake as client.\n",
1347 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, ctx->tc_is_server ) ) {
1348 Debug( LDAP_DEBUG_ANY,
1349 "TLS: could not set handshake as server.\n",
1354 if ( lt->lt_ciphersuite &&
1355 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
1356 Debug( LDAP_DEBUG_ANY,
1357 "TLS: could not set cipher list %s.\n",
1358 lt->lt_ciphersuite, 0, 0 );
1362 if ( ctx->tc_require_cert ) {
1363 request_cert = PR_TRUE;
1364 require_cert = SSL_REQUIRE_NO_ERROR;
1365 if ( ctx->tc_require_cert == LDAP_OPT_X_TLS_DEMAND ||
1366 ctx->tc_require_cert == LDAP_OPT_X_TLS_HARD ) {
1367 require_cert = SSL_REQUIRE_ALWAYS;
1369 ctx->tc_verify_cert = PR_TRUE;
1371 ctx->tc_verify_cert = PR_FALSE;
1374 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUEST_CERTIFICATE, request_cert ) ) {
1375 Debug( LDAP_DEBUG_ANY,
1376 "TLS: could not set request certificate mode.\n",
1381 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUIRE_CERTIFICATE, require_cert ) ) {
1382 Debug( LDAP_DEBUG_ANY,
1383 "TLS: could not set require certificate mode.\n",
1388 /* Set up callbacks for use by clients */
1389 if ( !ctx->tc_is_server ) {
1390 if ( SSL_OptionSet( ctx->tc_model, SSL_NO_CACHE, PR_TRUE ) != SECSuccess ) {
1391 PRErrorCode err = PR_GetError();
1392 Debug( LDAP_DEBUG_ANY,
1393 "TLS: error: could not set nocache option for moznss - error %d:%s\n",
1394 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1398 if ( SSL_BadCertHook( ctx->tc_model, tlsm_bad_cert_handler, ctx ) != SECSuccess ) {
1399 PRErrorCode err = PR_GetError();
1400 Debug( LDAP_DEBUG_ANY,
1401 "TLS: error: could not set bad cert handler for moznss - error %d:%s\n",
1402 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1406 /* we don't currently support import of cert/key pair - assume the certfile
1407 is really the name of a cert/key in the database in the form of
1408 tokenname:certname - also assume since this is specified, the caller
1409 wants to attempt client cert auth */
1410 if ( lt->lt_certfile ) {
1411 if ( tlsm_authenticate( ctx, lt->lt_certfile, lt->lt_keyfile ) ) {
1412 Debug( LDAP_DEBUG_ANY,
1413 "TLS: error: unable to authenticate to the security device for certificate %s\n",
1414 lt->lt_certfile, 0, 0 );
1417 if ( tlsm_clientauth_init( ctx, lt->lt_certfile ) ) {
1418 Debug( LDAP_DEBUG_ANY,
1419 "TLS: error: unable to set up client certificate authentication using %s\n",
1420 lt->lt_certfile, 0, 0 );
1424 } else { /* set up secure server */
1426 CERTCertificate *serverCert;
1427 SECKEYPrivateKey *serverKey;
1430 /* must have a certificate for the server to use */
1431 if ( !lt->lt_certfile ) {
1432 Debug( LDAP_DEBUG_ANY,
1433 "TLS: error: no server certificate: must specify a certificate for the server to use\n",
1438 /* authenticate to the server's token - this will do nothing
1439 if the key/cert db is not password protected */
1440 if ( tlsm_authenticate( ctx, lt->lt_certfile, lt->lt_keyfile ) ) {
1441 Debug( LDAP_DEBUG_ANY,
1442 "TLS: error: unable to authenticate to the security device for certificate %s\n",
1443 lt->lt_certfile, 0, 0 );
1447 /* get the server's key and cert */
1448 if ( tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, lt->lt_certfile, ctx->tc_is_server,
1449 &serverCert, &serverKey ) ) {
1450 Debug( LDAP_DEBUG_ANY,
1451 "TLS: error: unable to find and verify server's cert and key for certificate %s\n",
1452 lt->lt_certfile, 0, 0 );
1456 certKEA = NSS_FindCertKEAType( serverCert );
1457 /* configure the socket to be a secure server socket */
1458 status = SSL_ConfigSecureServer( ctx->tc_model, serverCert, serverKey, certKEA );
1459 /* SSL_ConfigSecureServer copies these */
1460 CERT_DestroyCertificate( serverCert );
1461 SECKEY_DestroyPrivateKey( serverKey );
1463 if ( SECSuccess != status ) {
1464 PRErrorCode err = PR_GetError();
1465 Debug( LDAP_DEBUG_ANY,
1466 "TLS: error: unable to configure secure server using certificate %s - error %d:%s\n",
1467 lt->lt_certfile, err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) );
1472 /* Callback for authenticating certificate */
1473 if ( SSL_AuthCertificateHook( ctx->tc_model, tlsm_auth_cert_handler,
1474 ctx->tc_certdb ) != SECSuccess ) {
1475 PRErrorCode err = PR_GetError();
1476 Debug( LDAP_DEBUG_ANY,
1477 "TLS: error: could not set auth cert handler for moznss - error %d:%s\n",
1478 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1486 tlsm_session *session;
1487 Sockbuf_IO_Desc *sbiod;
1488 /* there seems to be no portable way to determine if the
1489 sockbuf sd has been set to nonblocking mode - the
1490 call to ber_pvt_socket_set_nonblock() takes place
1491 before the tls socket is set up, so we cannot
1492 intercept that call either.
1493 On systems where fcntl is available, we can just
1494 F_GETFL and test for O_NONBLOCK. On other systems,
1495 we will just see if the IO op returns EAGAIN or EWOULDBLOCK,
1496 and just set this flag */
1501 tlsm_is_io_ready( PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags )
1504 PRFileDesc *pollfd = NULL;
1506 PRPollDesc polldesc;
1509 myfd = PR_GetIdentitiesLayer( fd, tlsm_layer_id );
1515 p = (struct tls_data *)myfd->secret;
1517 if ( p == NULL || p->sbiod == NULL ) {
1521 /* wrap the sockbuf fd with a NSPR FD created especially
1522 for use with polling, and only with polling */
1523 pollfd = PR_CreateSocketPollFd( p->sbiod->sbiod_sb->sb_fd );
1524 polldesc.fd = pollfd;
1525 polldesc.in_flags = in_flags;
1526 polldesc.out_flags = 0;
1528 /* do the poll - no waiting, no blocking */
1529 rc = PR_Poll( &polldesc, 1, PR_INTERVAL_NO_WAIT );
1531 /* unwrap the socket */
1532 PR_DestroySocketPollFd( pollfd );
1534 /* rc will be either 1 if IO is ready, 0 if IO is not
1535 ready, or -1 if there was some error (and the caller
1536 should use PR_GetError() to figure out what */
1538 *out_flags = polldesc.out_flags;
1543 static tls_session *
1544 tlsm_session_new ( tls_ctx * ctx, int is_server )
1546 tlsm_ctx *c = (tlsm_ctx *)ctx;
1547 tlsm_session *session;
1551 c->tc_is_server = is_server;
1552 status = PR_CallOnceWithArg( &c->tc_callonce, tlsm_deferred_ctx_init, c );
1553 if ( PR_SUCCESS != status ) {
1554 PRErrorCode err = PR_GetError();
1555 Debug( LDAP_DEBUG_ANY,
1556 "TLS: error: could not initialize moznss security context - error %d:%s\n",
1557 err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT), NULL );
1561 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
1566 session = SSL_ImportFD( c->tc_model, fd );
1573 /* 0 means use the defaults here */
1574 SSL_ConfigServerSessionIDCache( 0, 0, 0, NULL );
1577 return (tls_session *)session;
1581 tlsm_session_accept( tls_session *session )
1583 tlsm_session *s = (tlsm_session *)session;
1586 int waitcounter = 0;
1588 rc = SSL_ResetHandshake( s, PR_TRUE /* server */ );
1590 err = PR_GetError();
1591 Debug( LDAP_DEBUG_TRACE,
1592 "TLS: error: accept - reset handshake failure %d - error %d:%s\n",
1594 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1603 rc = SSL_ForceHandshake( s );
1604 if (rc == SECSuccess) {
1608 err = PR_GetError();
1609 Debug( LDAP_DEBUG_TRACE,
1610 "TLS: error: accept - force handshake failure %d - error %d waitcounter %d\n",
1611 errno, err, waitcounter );
1612 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
1614 in_flags = PR_POLL_READ | PR_POLL_EXCEPT;
1617 filesReady = tlsm_is_io_ready( s, in_flags, &out_flags );
1618 if ( filesReady < 0 ) {
1619 err = PR_GetError();
1620 Debug( LDAP_DEBUG_ANY,
1621 "TLS: error: accept - error waiting for socket to be ready: %d - error %d:%s\n",
1623 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1625 break; /* hard error */
1626 } else if ( out_flags & PR_POLL_NVAL ) {
1627 PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
1628 Debug( LDAP_DEBUG_ANY,
1629 "TLS: error: accept failure - invalid socket\n",
1633 } else if ( out_flags & PR_POLL_EXCEPT ) {
1634 err = PR_GetError();
1635 Debug( LDAP_DEBUG_ANY,
1636 "TLS: error: accept - error waiting for socket to be ready: %d - error %d:%s\n",
1638 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1640 break; /* hard error */
1642 } else { /* hard error */
1643 err = PR_GetError();
1644 Debug( LDAP_DEBUG_ANY,
1645 "TLS: error: accept - force handshake failure: %d - error %d:%s\n",
1647 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1649 break; /* hard error */
1651 } while (rc == SECFailure);
1653 Debug( LDAP_DEBUG_TRACE,
1654 "TLS: accept completed after %d waits\n", waitcounter, NULL, NULL );
1660 tlsm_session_connect( LDAP *ld, tls_session *session )
1662 tlsm_session *s = (tlsm_session *)session;
1666 /* By default, NSS checks the cert hostname for us */
1667 rc = SSL_ResetHandshake( s, PR_FALSE /* server */ );
1669 err = PR_GetError();
1670 Debug( LDAP_DEBUG_TRACE,
1671 "TLS: error: connect - reset handshake failure %d - error %d:%s\n",
1673 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1676 rc = SSL_SetURL( s, ld->ld_options.ldo_defludp->lud_host );
1678 err = PR_GetError();
1679 Debug( LDAP_DEBUG_TRACE,
1680 "TLS: error: connect - seturl failure %d - error %d:%s\n",
1682 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1685 rc = SSL_ForceHandshake( s );
1687 err = PR_GetError();
1688 Debug( LDAP_DEBUG_TRACE,
1689 "TLS: error: connect - force handshake failure %d - error %d:%s\n",
1691 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1698 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
1700 /* Should never happen */
1703 if ( rc != PR_PENDING_INTERRUPT_ERROR && rc != PR_WOULD_BLOCK_ERROR )
1709 tlsm_session_errmsg( int rc, char *buf, size_t len )
1714 i = PR_GetErrorTextLength();
1716 char *msg = LDAP_MALLOC( i+1 );
1717 PR_GetErrorText( msg );
1718 memcpy( buf, msg, len );
1721 PR_GetErrorText( buf );
1724 return i ? buf : NULL;
1728 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
1730 tlsm_session *s = (tlsm_session *)session;
1731 CERTCertificate *cert;
1733 cert = SSL_LocalCertificate( s );
1734 if (!cert) return LDAP_INVALID_CREDENTIALS;
1736 der_dn->bv_val = cert->derSubject.data;
1737 der_dn->bv_len = cert->derSubject.len;
1738 CERT_DestroyCertificate( cert );
1743 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
1745 tlsm_session *s = (tlsm_session *)session;
1746 CERTCertificate *cert;
1748 cert = SSL_PeerCertificate( s );
1749 if (!cert) return LDAP_INVALID_CREDENTIALS;
1751 der_dn->bv_val = cert->derSubject.data;
1752 der_dn->bv_len = cert->derSubject.len;
1753 CERT_DestroyCertificate( cert );
1758 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
1760 /* NSS already does a hostname check */
1761 return LDAP_SUCCESS;
1765 tlsm_session_strength( tls_session *session )
1767 tlsm_session *s = (tlsm_session *)session;
1770 rc = SSL_SecurityStatus( s, NULL, NULL, NULL, &keySize,
1772 return rc ? 0 : keySize;
1776 * TLS support for LBER Sockbufs
1779 static PRStatus PR_CALLBACK
1780 tlsm_PR_Close(PRFileDesc *fd)
1782 int rc = PR_SUCCESS;
1784 /* we don't need to actually close anything here, just
1785 pop our io layer off the stack */
1786 fd->secret = NULL; /* must have been freed before calling PR_Close */
1788 fd = PR_PopIOLayer( fd, tlsm_layer_id );
1789 /* if we are not the last layer, pass the close along */
1794 rc = fd->methods->close( fd );
1797 /* we are the last layer - just call our dtor */
1804 static PRStatus PR_CALLBACK
1805 tlsm_PR_Shutdown(PRFileDesc *fd, PRShutdownHow how)
1807 int rc = PR_SUCCESS;
1810 rc = PR_Shutdown( fd->lower, how );
1816 static int PR_CALLBACK
1817 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
1818 PRIntervalTime timeout)
1823 if ( buf == NULL || len <= 0 ) return 0;
1825 p = (struct tls_data *)fd->secret;
1827 if ( p == NULL || p->sbiod == NULL ) {
1831 rc = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
1833 tlsm_map_error( errno );
1834 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
1835 p->nonblock = PR_TRUE; /* fd is using non-blocking io */
1836 } else if ( errno ) { /* real error */
1837 Debug( LDAP_DEBUG_TRACE,
1838 "TLS: error: tlsm_PR_Recv returned %d - error %d:%s\n",
1839 rc, errno, STRERROR(errno) );
1846 static int PR_CALLBACK
1847 tlsm_PR_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
1848 PRIntervalTime timeout)
1853 if ( buf == NULL || len <= 0 ) return 0;
1855 p = (struct tls_data *)fd->secret;
1857 if ( p == NULL || p->sbiod == NULL ) {
1861 rc = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
1863 tlsm_map_error( errno );
1864 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
1865 p->nonblock = PR_TRUE;
1866 } else if ( errno ) { /* real error */
1867 Debug( LDAP_DEBUG_TRACE,
1868 "TLS: error: tlsm_PR_Send returned %d - error %d:%s\n",
1869 rc, errno, STRERROR(errno) );
1876 static int PR_CALLBACK
1877 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
1879 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
1882 static int PR_CALLBACK
1883 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
1885 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
1888 static PRStatus PR_CALLBACK
1889 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
1895 p = (struct tls_data *)fd->secret;
1897 if ( p == NULL || p->sbiod == NULL ) {
1900 len = sizeof(PRNetAddr);
1901 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
1904 static PRStatus PR_CALLBACK
1905 tlsm_PR_GetSocketOption(PRFileDesc *fd, PRSocketOptionData *data)
1908 p = (struct tls_data *)fd->secret;
1914 /* only the nonblocking option is supported at this time
1915 MozNSS SSL code needs it */
1916 if ( data->option != PR_SockOpt_Nonblocking ) {
1917 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1921 int flags = fcntl( p->sbiod->sbiod_sb->sb_fd, F_GETFL );
1922 data->value.non_blocking = (flags & O_NONBLOCK) ? PR_TRUE : PR_FALSE;
1924 data->value.non_blocking = p->nonblock;
1929 static PRStatus PR_CALLBACK
1932 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1936 static PRFileDesc * PR_CALLBACK
1939 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1943 static PRInt16 PR_CALLBACK
1946 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1950 static PRInt32 PR_CALLBACK
1953 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1957 static PRInt64 PR_CALLBACK
1962 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
1967 static const PRIOMethods tlsm_PR_methods = {
1969 tlsm_PR_Close, /* close */
1970 tlsm_PR_Read, /* read */
1971 tlsm_PR_Write, /* write */
1972 tlsm_PR_i32_unimp, /* available */
1973 tlsm_PR_i64_unimp, /* available64 */
1974 tlsm_PR_prs_unimp, /* fsync */
1975 tlsm_PR_i32_unimp, /* seek */
1976 tlsm_PR_i64_unimp, /* seek64 */
1977 tlsm_PR_prs_unimp, /* fileInfo */
1978 tlsm_PR_prs_unimp, /* fileInfo64 */
1979 tlsm_PR_i32_unimp, /* writev */
1980 tlsm_PR_prs_unimp, /* connect */
1981 tlsm_PR_pfd_unimp, /* accept */
1982 tlsm_PR_prs_unimp, /* bind */
1983 tlsm_PR_prs_unimp, /* listen */
1984 (PRShutdownFN)tlsm_PR_Shutdown, /* shutdown */
1985 tlsm_PR_Recv, /* recv */
1986 tlsm_PR_Send, /* send */
1987 tlsm_PR_i32_unimp, /* recvfrom */
1988 tlsm_PR_i32_unimp, /* sendto */
1989 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
1990 tlsm_PR_i32_unimp, /* acceptread */
1991 tlsm_PR_i32_unimp, /* transmitfile */
1992 tlsm_PR_prs_unimp, /* getsockname */
1993 tlsm_PR_GetPeerName, /* getpeername */
1994 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
1995 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
1996 tlsm_PR_GetSocketOption, /* getsocketoption */
1997 tlsm_PR_i32_unimp, /* setsocketoption */
1998 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
1999 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
2000 tlsm_PR_i32_unimp, /* reserved for future use */
2001 tlsm_PR_i32_unimp, /* reserved for future use */
2002 tlsm_PR_i32_unimp, /* reserved for future use */
2003 tlsm_PR_i32_unimp /* reserved for future use */
2007 * Initialize TLS subsystem. Should be called only once.
2014 tlsm_layer_id = PR_GetUniqueIdentity( "OpenLDAP" );
2016 /* see deferred init */
2021 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
2024 tlsm_session *session = arg;
2027 assert( sbiod != NULL );
2029 p = LBER_MALLOC( sizeof( *p ) );
2034 fd = PR_GetIdentitiesLayer( session, tlsm_layer_id );
2040 fd->secret = (PRFilePrivate *)p;
2041 p->session = session;
2043 sbiod->sbiod_pvt = p;
2048 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
2052 assert( sbiod != NULL );
2053 assert( sbiod->sbiod_pvt != NULL );
2055 p = (struct tls_data *)sbiod->sbiod_pvt;
2056 PR_Close( p->session );
2057 LBER_FREE( sbiod->sbiod_pvt );
2058 sbiod->sbiod_pvt = NULL;
2063 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
2067 assert( sbiod != NULL );
2068 assert( sbiod->sbiod_pvt != NULL );
2070 p = (struct tls_data *)sbiod->sbiod_pvt;
2071 PR_Shutdown( p->session, PR_SHUTDOWN_BOTH );
2076 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
2080 assert( sbiod != NULL );
2081 assert( sbiod->sbiod_pvt != NULL );
2083 p = (struct tls_data *)sbiod->sbiod_pvt;
2085 if ( opt == LBER_SB_OPT_GET_SSL ) {
2086 *((tlsm_session **)arg) = p->session;
2089 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
2090 if ( tlsm_is_io_ready( p->session, PR_POLL_READ, NULL ) > 0 ) {
2096 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
2100 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2106 assert( sbiod != NULL );
2107 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2109 p = (struct tls_data *)sbiod->sbiod_pvt;
2111 ret = PR_Recv( p->session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2113 err = PR_GetError();
2114 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2115 sbiod->sbiod_sb->sb_trans_needs_read = 1;
2116 sock_errset(EWOULDBLOCK);
2119 sbiod->sbiod_sb->sb_trans_needs_read = 0;
2125 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2131 assert( sbiod != NULL );
2132 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2134 p = (struct tls_data *)sbiod->sbiod_pvt;
2136 ret = PR_Send( p->session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2138 err = PR_GetError();
2139 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2140 sbiod->sbiod_sb->sb_trans_needs_write = 1;
2141 sock_errset(EWOULDBLOCK);
2145 sbiod->sbiod_sb->sb_trans_needs_write = 0;
2150 static Sockbuf_IO tlsm_sbio =
2152 tlsm_sb_setup, /* sbi_setup */
2153 tlsm_sb_remove, /* sbi_remove */
2154 tlsm_sb_ctrl, /* sbi_ctrl */
2155 tlsm_sb_read, /* sbi_read */
2156 tlsm_sb_write, /* sbi_write */
2157 tlsm_sb_close /* sbi_close */
2160 tls_impl ldap_int_tls_impl = {
2172 tlsm_session_connect,
2173 tlsm_session_accept,
2174 tlsm_session_upflags,
2175 tlsm_session_errmsg,
2177 tlsm_session_peer_dn,
2178 tlsm_session_chkhost,
2179 tlsm_session_strength,
2183 #ifdef LDAP_R_COMPILE
2192 #endif /* HAVE_MOZNSS */