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 */
56 #include <nspr/nspr.h>
57 #include <nspr/private/pprio.h>
60 #include <nss/sslerr.h>
61 #include <nss/sslproto.h>
62 #include <nss/pk11pub.h>
63 #include <nss/secerr.h>
64 #include <nss/keyhi.h>
65 #include <nss/secmod.h>
67 typedef struct tlsm_ctx {
70 PRBool tc_verify_cert;
71 CERTCertDBHandle *tc_certdb;
74 struct ldaptls *tc_config;
77 PRCallOnceType tc_callonce;
79 char *tc_slotname; /* if using pem */
81 ldap_pvt_thread_mutex_t tc_refmutex;
85 typedef PRFileDesc tlsm_session;
87 static PRDescIdentity tlsm_layer_id;
89 static const PRIOMethods tlsm_PR_methods;
91 static int tlsm_did_init;
93 static const char* pem_library = "nsspem";
94 static SECMODModule* pemMod = NULL;
96 #define DEFAULT_TOKEN_NAME "default"
97 /* sprintf format used to create token name */
98 #define TLSM_PEM_TOKEN_FMT "PEM Token #%ld"
100 static int tlsm_slot_count;
102 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
103 (x)->pValue=(v); (x)->ulValueLen = (l);
105 /* forward declaration */
106 static int tlsm_init( void );
108 #ifdef LDAP_R_COMPILE
111 tlsm_thr_init( void )
115 #endif /* LDAP_R_COMPILE */
118 tlsm_dump_cipher_info(PRFileDesc *fd)
122 for (ii = 0; ii < SSL_NumImplementedCiphers; ++ii) {
123 PRInt32 cipher = (PRInt32)SSL_ImplementedCiphers[ii];
124 PRBool enabled = PR_FALSE;
126 SSLCipherSuiteInfo info;
129 SSL_CipherPrefGet(fd, cipher, &enabled);
131 SSL_CipherPrefGetDefault(cipher, &enabled);
133 SSL_CipherPolicyGet(cipher, &policy);
134 SSL_GetCipherSuiteInfo(cipher, &info, (PRUintn)sizeof(info));
135 Debug( LDAP_DEBUG_TRACE,
136 "TLS: cipher: %d - %s, enabled: %d, ",
137 info.cipherSuite, info.cipherSuiteName, enabled );
138 Debug( LDAP_DEBUG_TRACE,
139 "policy: %d\n", policy, 0, 0 );
145 /* Cipher definitions */
147 char *ossl_name; /* The OpenSSL cipher name */
148 int num; /* The cipher id */
149 int attr; /* cipher attributes: algorithms, etc */
150 int version; /* protocol version valid for this cipher */
151 int bits; /* bits of strength */
152 int alg_bits; /* bits of the algorithm */
153 int strength; /* LOW, MEDIUM, HIGH */
154 int enabled; /* Enabled by default? */
157 /* cipher attributes */
158 #define SSL_kRSA 0x00000001L
159 #define SSL_aRSA 0x00000002L
160 #define SSL_aDSS 0x00000004L
161 #define SSL_DSS SSL_aDSS
162 #define SSL_eNULL 0x00000008L
163 #define SSL_DES 0x00000010L
164 #define SSL_3DES 0x00000020L
165 #define SSL_RC4 0x00000040L
166 #define SSL_RC2 0x00000080L
167 #define SSL_AES 0x00000100L
168 #define SSL_MD5 0x00000200L
169 #define SSL_SHA1 0x00000400L
170 #define SSL_SHA SSL_SHA1
171 #define SSL_RSA (SSL_kRSA|SSL_aRSA)
173 /* cipher strength */
174 #define SSL_NULL 0x00000001L
175 #define SSL_EXPORT40 0x00000002L
176 #define SSL_EXPORT56 0x00000004L
177 #define SSL_LOW 0x00000008L
178 #define SSL_MEDIUM 0x00000010L
179 #define SSL_HIGH 0x00000020L
181 #define SSL2 0x00000001L
182 #define SSL3 0x00000002L
183 /* OpenSSL treats SSL3 and TLSv1 the same */
186 /* Cipher translation */
187 static cipher_properties ciphers_def[] = {
189 {"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},
190 {"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},
191 {"RC4-MD5", SSL_EN_RC4_128_WITH_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL2, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
192 {"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},
193 {"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},
194 {"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},
197 {"RC4-MD5", SSL_RSA_WITH_RC4_128_MD5, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_MD5, SSL3, 128, 128, SSL_MEDIUM, SSL_ALLOWED},
198 {"RC4-SHA", SSL_RSA_WITH_RC4_128_SHA, SSL_kRSA|SSL_aRSA|SSL_RC4|SSL_SHA1, SSL3, 128, 128, SSL_MEDIUM, SSL_NOT_ALLOWED},
199 {"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},
200 {"DES-CBC-SHA", SSL_RSA_WITH_DES_CBC_SHA, SSL_kRSA|SSL_aRSA|SSL_DES|SSL_SHA1, SSL3, 56, 56, SSL_LOW, SSL_ALLOWED},
201 {"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},
202 {"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},
203 {"NULL-MD5", SSL_RSA_WITH_NULL_MD5, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_MD5, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
204 {"NULL-SHA", SSL_RSA_WITH_NULL_SHA, SSL_kRSA|SSL_aRSA|SSL_eNULL|SSL_SHA1, SSL3, 0, 0, SSL_NULL, SSL_NOT_ALLOWED},
207 {"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},
208 {"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},
209 {"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},
210 {"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},
213 #define ciphernum (sizeof(ciphers_def)/sizeof(cipher_properties))
215 /* given err which is the current errno, calls PR_SetError with
216 the corresponding NSPR error code */
218 tlsm_map_error(int err)
224 prError = PR_NO_ACCESS_RIGHTS_ERROR;
227 prError = PR_ADDRESS_IN_USE_ERROR;
230 prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
233 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
236 prError = PR_WOULD_BLOCK_ERROR;
239 * On QNX and Neutrino, EALREADY is defined as EBUSY.
241 #if EALREADY != EBUSY
243 prError = PR_ALREADY_INITIATED_ERROR;
247 prError = PR_BAD_DESCRIPTOR_ERROR;
251 prError = PR_IO_ERROR;
255 prError = PR_FILESYSTEM_MOUNTED_ERROR;
258 prError = PR_CONNECT_ABORTED_ERROR;
261 prError = PR_CONNECT_REFUSED_ERROR;
264 prError = PR_CONNECT_RESET_ERROR;
267 prError = PR_DEADLOCK_ERROR;
271 prError = PR_DIRECTORY_CORRUPTED_ERROR;
276 prError = PR_NO_DEVICE_SPACE_ERROR;
280 prError = PR_FILE_EXISTS_ERROR;
283 prError = PR_ACCESS_FAULT_ERROR;
286 prError = PR_FILE_TOO_BIG_ERROR;
289 prError = PR_HOST_UNREACHABLE_ERROR;
292 prError = PR_IN_PROGRESS_ERROR;
295 prError = PR_PENDING_INTERRUPT_ERROR;
298 prError = PR_INVALID_ARGUMENT_ERROR;
301 prError = PR_IO_ERROR;
304 prError = PR_IS_CONNECTED_ERROR;
307 prError = PR_IS_DIRECTORY_ERROR;
310 prError = PR_LOOP_ERROR;
313 prError = PR_PROC_DESC_TABLE_FULL_ERROR;
316 prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
319 prError = PR_INVALID_ARGUMENT_ERROR;
323 prError = PR_REMOTE_FILE_ERROR;
327 prError = PR_NAME_TOO_LONG_ERROR;
330 prError = PR_NETWORK_UNREACHABLE_ERROR;
333 prError = PR_SYS_DESC_TABLE_FULL_ERROR;
336 * On SCO OpenServer 5, ENOBUFS is defined as ENOSR.
338 #if defined(ENOBUFS) && (ENOBUFS != ENOSR)
340 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
344 prError = PR_FILE_NOT_FOUND_ERROR;
347 prError = PR_FILE_NOT_FOUND_ERROR;
350 prError = PR_FILE_IS_LOCKED_ERROR;
354 prError = PR_REMOTE_FILE_ERROR;
358 prError = PR_OUT_OF_MEMORY_ERROR;
361 prError = PR_INVALID_ARGUMENT_ERROR;
364 prError = PR_NO_DEVICE_SPACE_ERROR;
368 prError = PR_INSUFFICIENT_RESOURCES_ERROR;
372 prError = PR_NOT_CONNECTED_ERROR;
375 prError = PR_NOT_DIRECTORY_ERROR;
378 prError = PR_NOT_SOCKET_ERROR;
381 prError = PR_FILE_NOT_FOUND_ERROR;
384 prError = PR_NOT_TCP_SOCKET_ERROR;
388 prError = PR_BUFFER_OVERFLOW_ERROR;
392 prError = PR_NO_ACCESS_RIGHTS_ERROR;
395 prError = PR_CONNECT_RESET_ERROR;
399 prError = PR_IO_ERROR;
402 case EPROTONOSUPPORT:
403 prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
406 prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
409 prError = PR_INVALID_METHOD_ERROR;
412 prError = PR_READ_ONLY_FILESYSTEM_ERROR;
415 prError = PR_INVALID_METHOD_ERROR;
418 prError = PR_IO_TIMEOUT_ERROR;
420 #if EWOULDBLOCK != EAGAIN
422 prError = PR_WOULD_BLOCK_ERROR;
426 prError = PR_NOT_SAME_DEVICE_ERROR;
429 prError = PR_UNKNOWN_ERROR;
432 PR_SetError( prError, err );
436 * cipher_list is an integer array with the following values:
437 * -1: never enable this cipher
442 nss_parse_ciphers(const char *cipherstr, int cipher_list[ciphernum])
451 /* All disabled to start */
452 for (i=0; i<ciphernum; i++)
455 ciphertip = strdup(cipherstr);
456 cipher = ciphers = ciphertip;
458 while (ciphers && (strlen(ciphers))) {
459 while ((*cipher) && (isspace(*cipher)))
464 case '+': /* Add something */
468 case '-': /* Subtract something */
472 case '!': /* Disable something */
481 if ((ciphers = strchr(cipher, ':'))) {
485 /* Do the easy one first */
486 if (!strcmp(cipher, "ALL")) {
487 for (i=0; i<ciphernum; i++) {
488 if (!(ciphers_def[i].attr & SSL_eNULL))
489 cipher_list[i] = action;
491 } else if (!strcmp(cipher, "COMPLEMENTOFALL")) {
492 for (i=0; i<ciphernum; i++) {
493 if ((ciphers_def[i].attr & SSL_eNULL))
494 cipher_list[i] = action;
496 } else if (!strcmp(cipher, "DEFAULT")) {
497 for (i=0; i<ciphernum; i++) {
498 cipher_list[i] = ciphers_def[i].enabled == SSL_ALLOWED ? 1 : 0;
507 while (c && (strlen(c))) {
509 if ((c = strchr(cipher, '+'))) {
513 if (!strcmp(cipher, "RSA")) {
515 } else if ((!strcmp(cipher, "NULL")) || (!strcmp(cipher, "eNULL"))) {
517 } else if (!strcmp(cipher, "AES")) {
519 } else if (!strcmp(cipher, "3DES")) {
521 } else if (!strcmp(cipher, "DES")) {
523 } else if (!strcmp(cipher, "RC4")) {
525 } else if (!strcmp(cipher, "RC2")) {
527 } else if (!strcmp(cipher, "MD5")) {
529 } else if ((!strcmp(cipher, "SHA")) || (!strcmp(cipher, "SHA1"))) {
531 } else if (!strcmp(cipher, "SSLv2")) {
533 } else if (!strcmp(cipher, "SSLv3")) {
535 } else if (!strcmp(cipher, "TLSv1")) {
537 } else if (!strcmp(cipher, "HIGH")) {
538 strength |= SSL_HIGH;
539 } else if (!strcmp(cipher, "MEDIUM")) {
540 strength |= SSL_MEDIUM;
541 } else if (!strcmp(cipher, "LOW")) {
543 } else if ((!strcmp(cipher, "EXPORT")) || (!strcmp(cipher, "EXP"))) {
544 strength |= SSL_EXPORT40|SSL_EXPORT56;
545 } else if (!strcmp(cipher, "EXPORT40")) {
546 strength |= SSL_EXPORT40;
547 } else if (!strcmp(cipher, "EXPORT56")) {
548 strength |= SSL_EXPORT56;
556 /* If we have a mask, apply it. If not then perhaps they provided
557 * a specific cipher to enable.
559 if (mask || strength || protocol) {
560 for (i=0; i<ciphernum; i++) {
561 if (((ciphers_def[i].attr & mask) ||
562 (ciphers_def[i].strength & strength) ||
563 (ciphers_def[i].version & protocol)) &&
564 (cipher_list[i] != -1)) {
565 /* Enable the NULL ciphers only if explicity
567 if (ciphers_def[i].attr & SSL_eNULL) {
568 if (mask & SSL_eNULL)
569 cipher_list[i] = action;
571 cipher_list[i] = action;
575 for (i=0; i<ciphernum; i++) {
576 if (!strcmp(ciphers_def[i].ossl_name, cipher) &&
577 cipher_list[1] != -1)
578 cipher_list[i] = action;
587 /* See if any ciphers were enabled */
589 for (i=0; i<ciphernum; i++) {
590 if (cipher_list[i] == 1)
600 tlsm_parse_ciphers(tlsm_ctx *ctx, const char *str)
602 int cipher_state[ciphernum];
608 rv = nss_parse_ciphers(str, cipher_state);
611 /* First disable everything */
612 for (i = 0; i < SSL_NumImplementedCiphers; i++)
613 SSL_CipherPrefSet(ctx->tc_model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
615 /* Now enable what was requested */
616 for (i=0; i<ciphernum; i++) {
617 SSLCipherSuiteInfo suite;
620 if (SSL_GetCipherSuiteInfo(ciphers_def[i].num, &suite, sizeof suite)
622 enabled = cipher_state[i] < 0 ? 0 : cipher_state[i];
623 if (enabled == SSL_ALLOWED) {
624 if (PK11_IsFIPS() && !suite.isFIPS)
625 enabled = SSL_NOT_ALLOWED;
627 SSL_CipherPrefSet(ctx->tc_model, ciphers_def[i].num, enabled);
632 return rv == 1 ? 0 : -1;
636 tlsm_bad_cert_handler(void *arg, PRFileDesc *ssl)
638 SECStatus success = SECSuccess;
640 tlsm_ctx *ctx = (tlsm_ctx *)arg;
646 err = PORT_GetError();
649 case SEC_ERROR_UNTRUSTED_ISSUER:
650 case SEC_ERROR_UNKNOWN_ISSUER:
651 case SEC_ERROR_EXPIRED_CERTIFICATE:
652 if (ctx->tc_verify_cert) {
653 success = SECFailure;
656 /* we bypass NSS's hostname checks and do our own */
657 case SSL_ERROR_BAD_CERT_DOMAIN:
660 success = SECFailure;
668 tlsm_dump_security_status(PRFileDesc *fd)
670 char * cp; /* bulk cipher name */
671 char * ip; /* cert issuer DN */
672 char * sp; /* cert subject DN */
673 int op; /* High, Low, Off */
674 int kp0; /* total key bits */
675 int kp1; /* secret key bits */
676 SSL3Statistics * ssl3stats = SSL_GetStatistics();
678 SSL_SecurityStatus( fd, &op, &cp, &kp0, &kp1, &ip, &sp );
679 Debug( LDAP_DEBUG_TRACE,
680 "TLS certificate verification: subject: %s, issuer: %s, cipher: %s, ",
681 sp ? sp : "-unknown-", ip ? ip : "-unknown-", cp ? cp : "-unknown-" );
685 Debug( LDAP_DEBUG_TRACE,
686 "security level: %s, secret key bits: %d, total key bits: %d, ",
687 ((op == SSL_SECURITY_STATUS_ON_HIGH) ? "high" :
688 ((op == SSL_SECURITY_STATUS_ON_LOW) ? "low" : "off")),
691 Debug( LDAP_DEBUG_TRACE,
692 "cache hits: %ld, cache misses: %ld, cache not reusable: %ld\n",
693 ssl3stats->hch_sid_cache_hits, ssl3stats->hch_sid_cache_misses,
694 ssl3stats->hch_sid_cache_not_ok );
699 #ifdef READ_PASSWORD_FROM_FILE
701 tlsm_get_pin_from_file(const char *token_name, tlsm_ctx *ctx)
704 char *contents = NULL;
707 char *candidate = NULL;
708 PRFileInfo file_info;
709 PRFileDesc *pwd_fileptr = PR_Open( ctx->tc_pin_file, PR_RDONLY, 00400 );
711 /* open the password file */
712 if ( !pwd_fileptr ) {
713 PRErrorCode errcode = PR_GetError();
714 Debug( LDAP_DEBUG_ANY,
715 "TLS: could not open security pin file %s - error %d:%s.\n",
716 ctx->tc_pin_file, errcode,
717 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
721 /* get the file size */
722 if ( PR_SUCCESS != PR_GetFileInfo( ctx->tc_pin_file, &file_info ) ) {
723 PRErrorCode errcode = PR_GetError();
724 Debug( LDAP_DEBUG_ANY,
725 "TLS: could not get file info from pin file %s - error %d:%s.\n",
726 ctx->tc_pin_file, errcode,
727 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
731 /* create a buffer to hold the file contents */
732 if ( !( contents = PR_MALLOC( file_info.size + 1 ) ) ) {
733 PRErrorCode errcode = PR_GetError();
734 Debug( LDAP_DEBUG_ANY,
735 "TLS: could not alloc a buffer for contents of pin file %s - error %d:%s.\n",
736 ctx->tc_pin_file, errcode,
737 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
741 /* read file into the buffer */
742 if( PR_Read( pwd_fileptr, contents, file_info.size ) <= 0 ) {
743 PRErrorCode errcode = PR_GetError();
744 Debug( LDAP_DEBUG_ANY,
745 "TLS: could not read the file contents from pin file %s - error %d:%s.\n",
746 ctx->tc_pin_file, errcode,
747 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
751 /* format is [tokenname:]password EOL [tokenname:]password EOL ... */
752 /* if you want to use a password containing a colon character, use
753 the special tokenname "default" */
754 for ( line = PL_strtok_r( contents, "\r\n", &lasts ); line;
755 line = PL_strtok_r( NULL, "\r\n", &lasts ) ) {
759 continue; /* skip blank lines */
761 colon = PL_strchr( line, ':' );
763 if ( *(colon + 1) && token_name &&
764 !PL_strncmp( token_name, line, colon-line ) ) {
765 candidate = colon + 1; /* found a definite match */
767 } else if ( !PL_strncmp( DEFAULT_TOKEN_NAME, line, colon-line ) ) {
768 candidate = colon + 1; /* found possible match */
770 } else { /* no token name */
776 PR_Close( pwd_fileptr );
779 pwdstr = PL_strdup( candidate );
781 PL_strfree( contents );
785 #endif /* READ_PASSWORD_FROM_FILE */
787 #ifdef READ_PASSWORD_FROM_STDIN
789 * Turn the echoing off on a tty.
794 if ( isatty( fd ) ) {
796 tcgetattr( fd, &tio );
797 tio.c_lflag &= ~ECHO;
798 tcsetattr( fd, TCSAFLUSH, &tio );
803 * Turn the echoing on on a tty.
808 if ( isatty( fd ) ) {
810 tcgetattr( fd, &tio );
812 tcsetattr( fd, TCSAFLUSH, &tio );
813 tcsetattr( fd, TCSAFLUSH, &tio );
816 #endif /* READ_PASSWORD_FROM_STDIN */
819 * This does the actual work of reading the pin/password/pass phrase
822 tlsm_get_pin(PK11SlotInfo *slot, PRBool retry, tlsm_ctx *ctx)
824 char *token_name = NULL;
827 token_name = PK11_GetTokenName( slot );
828 #ifdef READ_PASSWORD_FROM_FILE
829 /* Try to get the passwords from the password file if it exists.
830 * THIS IS UNSAFE and is provided for convenience only. Without this
831 * capability the server would have to be started in foreground mode
832 * if using an encrypted key.
834 if ( ctx->tc_pin_file ) {
835 pwdstr = tlsm_get_pin_from_file( token_name, ctx );
837 #endif /* RETRIEVE_PASSWORD_FROM_FILE */
838 #ifdef READ_PASSWORD_FROM_STDIN
840 int infd = PR_FileDesc2NativeHandle( PR_STDIN );
841 int isTTY = isatty( infd );
842 unsigned char phrase[200];
843 /* Prompt for password */
846 "Please enter pin, password, or pass phrase for security token '%s': ",
847 token_name ? token_name : DEFAULT_TOKEN_NAME );
850 fgets( (char*)phrase, sizeof(phrase), stdin );
852 fprintf( stdout, "\n" );
855 /* stomp on newline */
856 phrase[strlen((char*)phrase)-1] = 0;
858 pwdstr = PL_strdup( (char*)phrase );
861 #endif /* READ_PASSWORD_FROM_STDIN */
866 * PKCS11 devices (including the internal softokn cert/key database)
867 * may be protected by a pin or password or even pass phrase
868 * MozNSS needs a way for the user to provide that
871 tlsm_pin_prompt(PK11SlotInfo *slot, PRBool retry, void *arg)
873 tlsm_ctx *ctx = (tlsm_ctx *)arg;
875 return tlsm_get_pin( slot, retry, ctx );
879 tlsm_auth_cert_handler(void *arg, PRFileDesc *fd,
880 PRBool checksig, PRBool isServer)
882 SECStatus ret = SSL_AuthCertificate(arg, fd, checksig, isServer);
884 tlsm_dump_security_status( fd );
885 Debug( LDAP_DEBUG_TRACE,
886 "TLS certificate verification: %s\n",
887 ret == SECSuccess ? "ok" : "bad", 0, 0 );
889 if ( ret != SECSuccess ) {
890 PRErrorCode errcode = PORT_GetError();
891 Debug( LDAP_DEBUG_ANY,
892 "TLS certificate verification: Error, %d: %s\n",
893 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 ) ;
900 tlsm_authenticate_to_slot( tlsm_ctx *ctx, PK11SlotInfo *slot )
904 if ( SECSuccess != PK11_Authenticate( slot, PR_FALSE, ctx ) ) {
905 char *token_name = PK11_GetTokenName( slot );
906 PRErrorCode errcode = PR_GetError();
907 Debug( LDAP_DEBUG_ANY,
908 "TLS: could not authenticate to the security token %s - error %d:%s.\n",
909 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
910 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
912 rc = 0; /* success */
919 tlsm_init_tokens( tlsm_ctx *ctx )
921 PK11SlotList *slotList;
922 PK11SlotListElement *listEntry;
925 slotList = PK11_GetAllTokens( CKM_INVALID_MECHANISM, PR_FALSE, PR_TRUE, NULL );
927 for ( listEntry = PK11_GetFirstSafe( slotList ); !rc && listEntry;
928 listEntry = listEntry->next) {
929 PK11SlotInfo *slot = listEntry->slot;
930 rc = tlsm_authenticate_to_slot( ctx, slot );
938 tlsm_init_pem_module( void )
941 char *fullname = NULL;
942 char *configstring = NULL;
944 /* get the system dependent library name */
945 fullname = PR_GetLibraryName( NULL, pem_library );
946 /* Load our PKCS#11 module */
947 configstring = PR_smprintf( "library=%s name=PEM parameters=\"\"", fullname );
948 PR_smprintf_free( fullname );
950 pemMod = SECMOD_LoadUserModule( configstring, NULL, PR_FALSE );
951 PR_smprintf_free( configstring );
953 if ( !pemMod || !pemMod->loaded ) {
955 SECMOD_DestroyModule( pemMod );
965 tlsm_add_cert_from_file( tlsm_ctx *ctx, const char *filename, PRBool isca )
968 PK11SlotInfo *slot = NULL;
969 PK11GenericObject *rv;
971 CK_ATTRIBUTE theTemplate[20];
972 CK_BBOOL cktrue = CK_TRUE;
973 CK_BBOOL ckfalse = CK_FALSE;
974 CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
975 char tmpslotname[64];
976 char *slotname = NULL;
977 const char *ptr = NULL;
978 char sep = PR_GetDirectorySeparator();
983 slotID = 0; /* CA and trust objects use slot 0 */
984 PR_snprintf( tmpslotname, sizeof(tmpslotname), TLSM_PEM_TOKEN_FMT, slotID );
985 slotname = tmpslotname;
987 if ( ctx->tc_slotname == NULL ) { /* need new slot */
988 slotID = ++tlsm_slot_count;
989 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
991 slotname = ctx->tc_slotname;
993 if ( ( ptr = PL_strrchr( filename, sep ) ) ) {
994 PL_strfree( ctx->tc_certname );
996 ctx->tc_certname = PR_smprintf( "%s:%s", slotname, ptr );
1000 slot = PK11_FindSlotByName( slotname );
1003 PRErrorCode errcode = PR_GetError();
1004 Debug( LDAP_DEBUG_ANY,
1005 "TLS: could not find the slot for certificate %s - error %d:%s.\n",
1006 ctx->tc_certname, errcode,
1007 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1011 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1012 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1013 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1015 PK11_SETATTRS( attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1017 PK11_SETATTRS( attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) ); attrs++;
1019 /* This loads the certificate in our PEM module into the appropriate
1022 rv = PK11_CreateGenericObject( slot, theTemplate, 4, PR_FALSE /* isPerm */ );
1024 PK11_FreeSlot( slot );
1027 PRErrorCode errcode = PR_GetError();
1028 Debug( LDAP_DEBUG_ANY,
1029 "TLS: could not add the certificate %s - error %d:%s.\n",
1030 ctx->tc_certname, errcode,
1031 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1039 tlsm_add_key_from_file( tlsm_ctx *ctx, const char *filename )
1042 PK11SlotInfo * slot = NULL;
1043 PK11GenericObject *rv;
1044 CK_ATTRIBUTE *attrs;
1045 CK_ATTRIBUTE theTemplate[20];
1046 CK_BBOOL cktrue = CK_TRUE;
1047 CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
1050 attrs = theTemplate;
1052 if ( ctx->tc_slotname == NULL ) { /* need new slot */
1053 slotID = ++tlsm_slot_count;
1054 ctx->tc_slotname = PR_smprintf( TLSM_PEM_TOKEN_FMT, slotID );
1056 slot = PK11_FindSlotByName( ctx->tc_slotname );
1059 PRErrorCode errcode = PR_GetError();
1060 Debug( LDAP_DEBUG_ANY,
1061 "TLS: could not find the slot %s for the private key - error %d:%s.\n",
1062 ctx->tc_slotname, errcode,
1063 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1067 PK11_SETATTRS( attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
1068 PK11_SETATTRS( attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
1069 PK11_SETATTRS( attrs, CKA_LABEL, (unsigned char *)filename, strlen(filename)+1 ); attrs++;
1070 rv = PK11_CreateGenericObject( slot, theTemplate, 3, PR_FALSE /* isPerm */ );
1073 PRErrorCode errcode = PR_GetError();
1074 Debug( LDAP_DEBUG_ANY,
1075 "TLS: could not add the certificate %s - error %d:%s.\n",
1076 ctx->tc_certname, errcode,
1077 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1080 /* When adding an encrypted key the PKCS#11 will be set as removed */
1081 /* This will force the token to be seen as re-inserted */
1082 SECMOD_WaitForAnyTokenEvent( pemMod, 0, 0 );
1083 PK11_IsPresent( slot );
1087 PK11_FreeSlot( slot );
1093 tlsm_init_ca_certs( tlsm_ctx *ctx, const char *cacertfile, const char *cacertdir )
1095 PRBool isca = PR_TRUE;
1098 int rc = tlsm_add_cert_from_file( ctx, cacertfile, isca );
1110 memset( &fi, 0, sizeof(fi) );
1111 status = PR_GetFileInfo( cacertdir, &fi );
1112 if ( PR_SUCCESS != status) {
1113 PRErrorCode errcode = PR_GetError();
1114 Debug( LDAP_DEBUG_ANY,
1115 "TLS: could not get info about the CA certificate directory %s - error %d:%s.\n",
1117 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1121 if ( fi.type != PR_FILE_DIRECTORY ) {
1122 Debug( LDAP_DEBUG_ANY,
1123 "TLS: error: the CA certificate directory %s is not a directory.\n",
1128 dir = PR_OpenDir( cacertdir );
1129 if ( NULL == dir ) {
1130 PRErrorCode errcode = PR_GetError();
1131 Debug( LDAP_DEBUG_ANY,
1132 "TLS: could not open the CA certificate directory %s - error %d:%s.\n",
1134 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1140 entry = PR_ReadDir( dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN );
1141 if ( NULL != entry ) {
1142 char *fullpath = PR_smprintf( "%s/%s", cacertdir, entry->name );
1143 if ( !tlsm_add_cert_from_file( ctx, fullpath, isca ) ) {
1144 status = 0; /* found at least 1 valid CA file in the dir */
1146 PR_smprintf_free( fullpath );
1148 } while ( NULL != entry );
1152 PRErrorCode errcode = PR_GetError();
1153 Debug( LDAP_DEBUG_ANY,
1154 "TLS: did not find any valid CA certificate files in the CA certificate directory %s - error %d:%s.\n",
1156 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1165 * This is the part of the init we defer until we get the
1166 * actual security configuration information. This is
1167 * only called once, protected by a PRCallOnce
1168 * NOTE: This must be done before the first call to SSL_ImportFD,
1169 * especially the setting of the policy
1170 * NOTE: This must be called after fork()
1173 tlsm_deferred_init( void *arg )
1175 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1176 struct ldaptls *lt = ctx->tc_config;
1177 const char *securitydirs[3];
1180 PRErrorCode errcode = 1;
1182 /* NSS support for multi-init is coming */
1183 #ifndef NSS_MULTI_INIT
1184 if ( !NSS_IsInitialized() ) {
1185 #endif /* NSS_MULTI_INIT */
1187 MOZNSS_DIR will override everything else - you can
1188 always set MOZNSS_DIR to force the use of this
1190 If using MOZNSS, specify the location of the moznss db dir
1191 in the cacertdir directive of the OpenLDAP configuration.
1192 DEFAULT_MOZNSS_DIR will only be used if the code cannot
1193 find a security dir to use based on the current
1197 securitydirs[nn++] = PR_GetEnv( "MOZNSS_DIR" );
1198 securitydirs[nn++] = lt->lt_cacertdir;
1199 securitydirs[nn++] = PR_GetEnv( "DEFAULT_MOZNSS_DIR" );
1200 for (ii = 0; ii < nn; ++ii) {
1201 const char *securitydir = securitydirs[ii];
1202 if ( NULL == securitydir ) {
1205 if ( NSS_Initialize( securitydir, "", "", SECMOD_DB, NSS_INIT_READONLY ) ) {
1206 errcode = PORT_GetError();
1207 Debug( LDAP_DEBUG_TRACE,
1208 "TLS: could not initialize moznss using security dir %s - error %d:%s.\n",
1209 securitydir, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1212 Debug( LDAP_DEBUG_TRACE, "TLS: using moznss security dir %s.\n",
1213 securitydir, 0, 0 );
1219 if ( errcode ) { /* no moznss db found, or not using moznss db */
1220 if ( NSS_NoDB_Init( NULL ) ) {
1221 errcode = PORT_GetError();
1222 Debug( LDAP_DEBUG_ANY,
1223 "TLS: could not initialize moznss - error %d:%s.\n",
1224 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1228 /* initialize the PEM module */
1229 if ( tlsm_init_pem_module() ) {
1230 errcode = PORT_GetError();
1231 Debug( LDAP_DEBUG_ANY,
1232 "TLS: could not initialize moznss PEM module - error %d:%s.\n",
1233 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), 0 );
1237 if ( tlsm_init_ca_certs( ctx, lt->lt_cacertfile, lt->lt_cacertdir ) ) {
1241 ctx->tc_using_pem = PR_TRUE;
1244 NSS_SetDomesticPolicy();
1246 PK11_SetPasswordFunc( tlsm_pin_prompt );
1248 if ( tlsm_init_tokens( ctx ) ) {
1252 tlsm_did_init = 1; /* we did the init - we should also clean up */
1253 #ifndef NSS_MULTI_INIT
1255 #endif /* NSS_MULTI_INIT */
1261 tlsm_authenticate( tlsm_ctx *ctx, const char *certname, const char *pininfo )
1263 const char *colon = NULL;
1264 char *token_name = NULL;
1265 PK11SlotInfo *slot = NULL;
1268 if ( !certname || !*certname ) {
1272 if ( ( colon = PL_strchr( certname, ':' ) ) ) {
1273 token_name = PL_strndup( certname, colon-certname );
1277 slot = PK11_FindSlotByName( token_name );
1279 slot = PK11_GetInternalKeySlot();
1283 PRErrorCode errcode = PR_GetError();
1284 Debug( LDAP_DEBUG_ANY,
1285 "TLS: could not find the slot for security token %s - error %d:%s.\n",
1286 token_name ? token_name : DEFAULT_TOKEN_NAME, errcode,
1287 PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1291 rc = tlsm_authenticate_to_slot( ctx, slot );
1294 PL_strfree( token_name );
1296 PK11_FreeSlot( slot );
1303 * Find and verify the certificate.
1304 * Either fd is given, in which case the cert will be taken from it via SSL_PeerCertificate
1305 * or certname is given, and it will be searched for by name
1308 tlsm_find_and_verify_cert_key(tlsm_ctx *ctx, PRFileDesc *fd, const char *certname, int isServer, CERTCertificate **pRetCert, SECKEYPrivateKey **pRetKey)
1310 CERTCertificate *cert = NULL;
1312 void *pin_arg = NULL;
1313 SECKEYPrivateKey *key = NULL;
1315 pin_arg = SSL_RevealPinArg( fd );
1317 cert = PK11_FindCertFromNickname( certname, pin_arg );
1319 PRErrorCode errcode = PR_GetError();
1320 Debug( LDAP_DEBUG_ANY,
1321 "TLS: error: the certificate %s could not be found in the database - error %d:%s\n",
1322 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1326 /* we are verifying the peer cert
1327 we also need to swap the isServer meaning */
1328 cert = SSL_PeerCertificate( fd );
1330 PRErrorCode errcode = PR_GetError();
1331 Debug( LDAP_DEBUG_ANY,
1332 "TLS: error: could not get the certificate from the peer connection - error %d:%s\n",
1333 errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ), NULL );
1336 isServer = !isServer; /* verify the peer's cert instead */
1339 if ( ctx->tc_slotname ) {
1340 PK11SlotInfo *slot = PK11_FindSlotByName( ctx->tc_slotname );
1341 key = PK11_FindPrivateKeyFromCert( slot, cert, NULL );
1342 PK11_FreeSlot( slot );
1344 key = PK11_FindKeyByAnyCert( cert, pin_arg );
1348 SECCertificateUsage certUsage;
1349 PRBool checkSig = PR_TRUE;
1353 *pRetKey = key; /* caller will deal with this */
1355 SECKEY_DestroyPrivateKey( key );
1358 certUsage = certificateUsageSSLServer;
1360 certUsage = certificateUsageSSLClient;
1362 if ( ctx->tc_verify_cert ) {
1365 checkSig = PR_FALSE;
1367 status = CERT_VerifyCertificateNow( ctx->tc_certdb, cert,
1368 checkSig, certUsage,
1370 if (status != SECSuccess) {
1371 PRErrorCode errcode = PR_GetError();
1372 Debug( LDAP_DEBUG_ANY,
1373 "TLS: error: the certificate %s is not valid - error %d:%s\n",
1374 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1376 rc = 0; /* success */
1379 PRErrorCode errcode = PR_GetError();
1380 Debug( LDAP_DEBUG_ANY,
1381 "TLS: error: could not find the private key for certificate %s - error %d:%s\n",
1382 certname, errcode, PR_ErrorToString( errcode, PR_LANGUAGE_I_DEFAULT ) );
1386 *pRetCert = cert; /* caller will deal with this */
1388 CERT_DestroyCertificate( cert );
1395 tlsm_get_client_auth_data( void *arg, PRFileDesc *fd,
1396 CERTDistNames *caNames, CERTCertificate **pRetCert,
1397 SECKEYPrivateKey **pRetKey )
1399 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1402 /* don't need caNames - this function will call CERT_VerifyCertificateNow
1403 which will verify the cert against the known CAs */
1404 rc = tlsm_find_and_verify_cert_key( ctx, fd, ctx->tc_certname, 0, pRetCert, pRetKey );
1406 Debug( LDAP_DEBUG_ANY,
1407 "TLS: error: unable to perform client certificate authentication for "
1408 "certificate named %s\n", ctx->tc_certname, 0, 0 );
1416 * ctx must have a tc_model that is valid
1417 * certname is in the form [<tokenname>:]<certnickname>
1418 * where <tokenname> is the name of the PKCS11 token
1419 * and <certnickname> is the nickname of the cert/key in
1423 tlsm_clientauth_init( tlsm_ctx *ctx, const char *certname )
1425 SECStatus status = SECFailure;
1428 PL_strfree( ctx->tc_certname );
1429 rc = tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, certname, 0, NULL, NULL );
1431 Debug( LDAP_DEBUG_ANY,
1432 "TLS: error: unable to set up client certificate authentication for "
1433 "certificate named %s\n", certname, 0, 0 );
1437 ctx->tc_certname = PL_strdup( certname );
1439 status = SSL_GetClientAuthDataHook( ctx->tc_model,
1440 tlsm_get_client_auth_data,
1443 return ( status == SECSuccess ? 0 : -1 );
1447 * Tear down the TLS subsystem. Should only be called once.
1450 tlsm_destroy( void )
1453 SECMOD_DestroyModule(pemMod);
1457 /* Only if we did the actual initialization */
1458 if ( tlsm_did_init ) {
1461 SSL_ShutdownServerSessionIDCache();
1462 SSL_ClearSessionCache();
1470 tlsm_ctx_new ( struct ldapoptions *lo )
1474 ctx = LDAP_MALLOC( sizeof (*ctx) );
1477 #ifdef LDAP_R_COMPILE
1478 ldap_pvt_thread_mutex_init( &ctx->tc_refmutex );
1480 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 */
1481 ctx->tc_certdb = NULL;
1482 ctx->tc_certname = NULL;
1483 ctx->tc_pin_file = NULL;
1484 ctx->tc_model = NULL;
1485 memset(&ctx->tc_callonce, 0, sizeof(ctx->tc_callonce));
1486 ctx->tc_require_cert = lo->ldo_tls_require_cert;
1487 ctx->tc_verify_cert = PR_FALSE;
1488 ctx->tc_using_pem = PR_FALSE;
1489 ctx->tc_slotname = NULL;
1491 return (tls_ctx *)ctx;
1495 tlsm_ctx_ref( tls_ctx *ctx )
1497 tlsm_ctx *c = (tlsm_ctx *)ctx;
1498 #ifdef LDAP_R_COMPILE
1499 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
1502 #ifdef LDAP_R_COMPILE
1503 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
1508 tlsm_ctx_free ( tls_ctx *ctx )
1510 tlsm_ctx *c = (tlsm_ctx *)ctx;
1515 #ifdef LDAP_R_COMPILE
1516 ldap_pvt_thread_mutex_lock( &c->tc_refmutex );
1518 refcount = --c->tc_refcnt;
1519 #ifdef LDAP_R_COMPILE
1520 ldap_pvt_thread_mutex_unlock( &c->tc_refmutex );
1525 PR_Close( c->tc_model );
1526 c->tc_certdb = NULL; /* if not the default, may have to clean up */
1527 PL_strfree( c->tc_certname );
1528 c->tc_certname = NULL;
1529 PL_strfree( c->tc_pin_file );
1530 c->tc_pin_file = NULL;
1531 PL_strfree( c->tc_slotname );
1532 #ifdef LDAP_R_COMPILE
1533 ldap_pvt_thread_mutex_destroy( &c->tc_refmutex );
1539 * initialize a new TLS context
1542 tlsm_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
1544 tlsm_ctx *ctx = (tlsm_ctx *)lo->ldo_tls_ctx;
1545 ctx->tc_is_server = is_server;
1551 tlsm_deferred_ctx_init( void *arg )
1553 tlsm_ctx *ctx = (tlsm_ctx *)arg;
1554 PRBool sslv2 = PR_FALSE;
1555 PRBool sslv3 = PR_TRUE;
1556 PRBool tlsv1 = PR_TRUE;
1557 PRBool request_cert = PR_FALSE;
1558 PRInt32 require_cert = PR_FALSE;
1562 if ( tlsm_deferred_init( ctx ) ) {
1563 Debug( LDAP_DEBUG_ANY,
1564 "TLS: could perform TLS system initialization.\n",
1569 ctx->tc_certdb = CERT_GetDefaultCertDB(); /* replace with multi-init db call */
1571 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
1573 ctx->tc_model = SSL_ImportFD( NULL, fd );
1576 if ( !ctx->tc_model ) {
1577 PRErrorCode err = PR_GetError();
1578 Debug( LDAP_DEBUG_ANY,
1579 "TLS: could perform TLS socket I/O layer initialization - error %d:%s.\n",
1580 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1588 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_SECURITY, PR_TRUE ) ) {
1589 Debug( LDAP_DEBUG_ANY,
1590 "TLS: could not set secure mode on.\n",
1595 lt = ctx->tc_config;
1597 /* default is sslv3 and tlsv1 */
1598 if ( lt->lt_protocol_min ) {
1599 if ( lt->lt_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 ) {
1601 } else if ( lt->lt_protocol_min <= LDAP_OPT_X_TLS_PROTOCOL_SSL2 ) {
1603 Debug( LDAP_DEBUG_ANY,
1604 "TLS: warning: minimum TLS protocol level set to "
1605 "include SSLv2 - SSLv2 is insecure - do not use\n", 0, 0, 0 );
1608 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL2, sslv2 ) ) {
1609 Debug( LDAP_DEBUG_ANY,
1610 "TLS: could not set SSLv2 mode on.\n",
1614 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_SSL3, sslv3 ) ) {
1615 Debug( LDAP_DEBUG_ANY,
1616 "TLS: could not set SSLv3 mode on.\n",
1620 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_ENABLE_TLS, tlsv1 ) ) {
1621 Debug( LDAP_DEBUG_ANY,
1622 "TLS: could not set TLSv1 mode on.\n",
1627 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_CLIENT, !ctx->tc_is_server ) ) {
1628 Debug( LDAP_DEBUG_ANY,
1629 "TLS: could not set handshake as client.\n",
1633 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_HANDSHAKE_AS_SERVER, ctx->tc_is_server ) ) {
1634 Debug( LDAP_DEBUG_ANY,
1635 "TLS: could not set handshake as server.\n",
1640 if ( lt->lt_ciphersuite &&
1641 tlsm_parse_ciphers( ctx, lt->lt_ciphersuite )) {
1642 Debug( LDAP_DEBUG_ANY,
1643 "TLS: could not set cipher list %s.\n",
1644 lt->lt_ciphersuite, 0, 0 );
1648 if ( ctx->tc_require_cert ) {
1649 request_cert = PR_TRUE;
1650 require_cert = SSL_REQUIRE_NO_ERROR;
1651 if ( ctx->tc_require_cert == LDAP_OPT_X_TLS_DEMAND ||
1652 ctx->tc_require_cert == LDAP_OPT_X_TLS_HARD ) {
1653 require_cert = SSL_REQUIRE_ALWAYS;
1655 if ( ctx->tc_require_cert != LDAP_OPT_X_TLS_ALLOW )
1656 ctx->tc_verify_cert = PR_TRUE;
1658 ctx->tc_verify_cert = PR_FALSE;
1661 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUEST_CERTIFICATE, request_cert ) ) {
1662 Debug( LDAP_DEBUG_ANY,
1663 "TLS: could not set request certificate mode.\n",
1668 if ( SECSuccess != SSL_OptionSet( ctx->tc_model, SSL_REQUIRE_CERTIFICATE, require_cert ) ) {
1669 Debug( LDAP_DEBUG_ANY,
1670 "TLS: could not set require certificate mode.\n",
1675 /* set up our cert and key, if any */
1676 if ( lt->lt_certfile ) {
1677 /* if using the PEM module, load the PEM file specified by lt_certfile */
1678 /* otherwise, assume this is the name of a cert already in the db */
1679 if ( ctx->tc_using_pem ) {
1680 /* this sets ctx->tc_certname to the correct value */
1681 int rc = tlsm_add_cert_from_file( ctx, lt->lt_certfile, PR_FALSE /* not a ca */ );
1686 PL_strfree( ctx->tc_certname );
1687 ctx->tc_certname = PL_strdup( lt->lt_certfile );
1691 if ( lt->lt_keyfile ) {
1692 /* if using the PEM module, load the PEM file specified by lt_keyfile */
1693 /* otherwise, assume this is the pininfo for the key */
1694 if ( ctx->tc_using_pem ) {
1695 /* this sets ctx->tc_certname to the correct value */
1696 int rc = tlsm_add_key_from_file( ctx, lt->lt_keyfile );
1701 PL_strfree( ctx->tc_pin_file );
1702 ctx->tc_pin_file = PL_strdup( lt->lt_keyfile );
1706 /* Set up callbacks for use by clients */
1707 if ( !ctx->tc_is_server ) {
1708 if ( SSL_OptionSet( ctx->tc_model, SSL_NO_CACHE, PR_TRUE ) != SECSuccess ) {
1709 PRErrorCode err = PR_GetError();
1710 Debug( LDAP_DEBUG_ANY,
1711 "TLS: error: could not set nocache option for moznss - error %d:%s\n",
1712 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1716 if ( SSL_BadCertHook( ctx->tc_model, tlsm_bad_cert_handler, ctx ) != SECSuccess ) {
1717 PRErrorCode err = PR_GetError();
1718 Debug( LDAP_DEBUG_ANY,
1719 "TLS: error: could not set bad cert handler for moznss - error %d:%s\n",
1720 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1725 since a cert has been specified, assume the client wants to do cert auth
1727 if ( ctx->tc_certname ) {
1728 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
1729 Debug( LDAP_DEBUG_ANY,
1730 "TLS: error: unable to authenticate to the security device for certificate %s\n",
1731 ctx->tc_certname, 0, 0 );
1734 if ( tlsm_clientauth_init( ctx, ctx->tc_certname ) ) {
1735 Debug( LDAP_DEBUG_ANY,
1736 "TLS: error: unable to set up client certificate authentication using %s\n",
1737 ctx->tc_certname, 0, 0 );
1741 } else { /* set up secure server */
1743 CERTCertificate *serverCert;
1744 SECKEYPrivateKey *serverKey;
1747 /* must have a certificate for the server to use */
1748 if ( !ctx->tc_certname ) {
1749 Debug( LDAP_DEBUG_ANY,
1750 "TLS: error: no server certificate: must specify a certificate for the server to use\n",
1755 /* authenticate to the server's token - this will do nothing
1756 if the key/cert db is not password protected */
1757 if ( tlsm_authenticate( ctx, ctx->tc_certname, ctx->tc_pin_file ) ) {
1758 Debug( LDAP_DEBUG_ANY,
1759 "TLS: error: unable to authenticate to the security device for certificate %s\n",
1760 ctx->tc_certname, 0, 0 );
1764 /* get the server's key and cert */
1765 if ( tlsm_find_and_verify_cert_key( ctx, ctx->tc_model, ctx->tc_certname, ctx->tc_is_server,
1766 &serverCert, &serverKey ) ) {
1767 Debug( LDAP_DEBUG_ANY,
1768 "TLS: error: unable to find and verify server's cert and key for certificate %s\n",
1769 ctx->tc_certname, 0, 0 );
1773 certKEA = NSS_FindCertKEAType( serverCert );
1774 /* configure the socket to be a secure server socket */
1775 status = SSL_ConfigSecureServer( ctx->tc_model, serverCert, serverKey, certKEA );
1776 /* SSL_ConfigSecureServer copies these */
1777 CERT_DestroyCertificate( serverCert );
1778 SECKEY_DestroyPrivateKey( serverKey );
1780 if ( SECSuccess != status ) {
1781 PRErrorCode err = PR_GetError();
1782 Debug( LDAP_DEBUG_ANY,
1783 "TLS: error: unable to configure secure server using certificate %s - error %d:%s\n",
1784 ctx->tc_certname, err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) );
1789 /* Callback for authenticating certificate */
1790 if ( SSL_AuthCertificateHook( ctx->tc_model, tlsm_auth_cert_handler,
1791 ctx->tc_certdb ) != SECSuccess ) {
1792 PRErrorCode err = PR_GetError();
1793 Debug( LDAP_DEBUG_ANY,
1794 "TLS: error: could not set auth cert handler for moznss - error %d:%s\n",
1795 err, PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ), NULL );
1803 tlsm_session *session;
1804 Sockbuf_IO_Desc *sbiod;
1805 /* there seems to be no portable way to determine if the
1806 sockbuf sd has been set to nonblocking mode - the
1807 call to ber_pvt_socket_set_nonblock() takes place
1808 before the tls socket is set up, so we cannot
1809 intercept that call either.
1810 On systems where fcntl is available, we can just
1811 F_GETFL and test for O_NONBLOCK. On other systems,
1812 we will just see if the IO op returns EAGAIN or EWOULDBLOCK,
1813 and just set this flag */
1818 tlsm_is_io_ready( PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags )
1821 PRFileDesc *pollfd = NULL;
1823 PRPollDesc polldesc;
1826 myfd = PR_GetIdentitiesLayer( fd, tlsm_layer_id );
1832 p = (struct tls_data *)myfd->secret;
1834 if ( p == NULL || p->sbiod == NULL ) {
1838 /* wrap the sockbuf fd with a NSPR FD created especially
1839 for use with polling, and only with polling */
1840 pollfd = PR_CreateSocketPollFd( p->sbiod->sbiod_sb->sb_fd );
1841 polldesc.fd = pollfd;
1842 polldesc.in_flags = in_flags;
1843 polldesc.out_flags = 0;
1845 /* do the poll - no waiting, no blocking */
1846 rc = PR_Poll( &polldesc, 1, PR_INTERVAL_NO_WAIT );
1848 /* unwrap the socket */
1849 PR_DestroySocketPollFd( pollfd );
1851 /* rc will be either 1 if IO is ready, 0 if IO is not
1852 ready, or -1 if there was some error (and the caller
1853 should use PR_GetError() to figure out what */
1855 *out_flags = polldesc.out_flags;
1860 static tls_session *
1861 tlsm_session_new ( tls_ctx * ctx, int is_server )
1863 tlsm_ctx *c = (tlsm_ctx *)ctx;
1864 tlsm_session *session;
1868 c->tc_is_server = is_server;
1869 status = PR_CallOnceWithArg( &c->tc_callonce, tlsm_deferred_ctx_init, c );
1870 if ( PR_SUCCESS != status ) {
1871 PRErrorCode err = PR_GetError();
1872 Debug( LDAP_DEBUG_ANY,
1873 "TLS: error: could not initialize moznss security context - error %d:%s\n",
1874 err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT), NULL );
1878 fd = PR_CreateIOLayerStub( tlsm_layer_id, &tlsm_PR_methods );
1883 session = SSL_ImportFD( c->tc_model, fd );
1890 /* 0 means use the defaults here */
1891 SSL_ConfigServerSessionIDCache( 0, 0, 0, NULL );
1894 return (tls_session *)session;
1898 tlsm_session_accept( tls_session *session )
1900 tlsm_session *s = (tlsm_session *)session;
1903 int waitcounter = 0;
1905 rc = SSL_ResetHandshake( s, PR_TRUE /* server */ );
1907 err = PR_GetError();
1908 Debug( LDAP_DEBUG_TRACE,
1909 "TLS: error: accept - reset handshake failure %d - error %d:%s\n",
1911 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1920 rc = SSL_ForceHandshake( s );
1921 if (rc == SECSuccess) {
1925 err = PR_GetError();
1926 Debug( LDAP_DEBUG_TRACE,
1927 "TLS: error: accept - force handshake failure %d - error %d waitcounter %d\n",
1928 errno, err, waitcounter );
1929 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
1931 in_flags = PR_POLL_READ | PR_POLL_EXCEPT;
1934 filesReady = tlsm_is_io_ready( s, in_flags, &out_flags );
1935 if ( filesReady < 0 ) {
1936 err = PR_GetError();
1937 Debug( LDAP_DEBUG_ANY,
1938 "TLS: error: accept - error waiting for socket to be ready: %d - error %d:%s\n",
1940 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1942 break; /* hard error */
1943 } else if ( out_flags & PR_POLL_NVAL ) {
1944 PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
1945 Debug( LDAP_DEBUG_ANY,
1946 "TLS: error: accept failure - invalid socket\n",
1950 } else if ( out_flags & PR_POLL_EXCEPT ) {
1951 err = PR_GetError();
1952 Debug( LDAP_DEBUG_ANY,
1953 "TLS: error: accept - error waiting for socket to be ready: %d - error %d:%s\n",
1955 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1957 break; /* hard error */
1959 } else { /* hard error */
1960 err = PR_GetError();
1961 Debug( LDAP_DEBUG_ANY,
1962 "TLS: error: accept - force handshake failure: %d - error %d:%s\n",
1964 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1966 break; /* hard error */
1968 } while (rc == SECFailure);
1970 Debug( LDAP_DEBUG_TRACE,
1971 "TLS: accept completed after %d waits\n", waitcounter, NULL, NULL );
1977 tlsm_session_connect( LDAP *ld, tls_session *session )
1979 tlsm_session *s = (tlsm_session *)session;
1983 rc = SSL_ResetHandshake( s, PR_FALSE /* server */ );
1985 err = PR_GetError();
1986 Debug( LDAP_DEBUG_TRACE,
1987 "TLS: error: connect - reset handshake failure %d - error %d:%s\n",
1989 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
1992 rc = SSL_ForceHandshake( s );
1994 err = PR_GetError();
1995 Debug( LDAP_DEBUG_TRACE,
1996 "TLS: error: connect - force handshake failure %d - error %d:%s\n",
1998 err ? PR_ErrorToString( err, PR_LANGUAGE_I_DEFAULT ) : "unknown" );
2005 tlsm_session_upflags( Sockbuf *sb, tls_session *session, int rc )
2007 /* Should never happen */
2010 if ( rc != PR_PENDING_INTERRUPT_ERROR && rc != PR_WOULD_BLOCK_ERROR )
2016 tlsm_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
2021 i = PR_GetErrorTextLength();
2023 char *msg = LDAP_MALLOC( i+1 );
2024 PR_GetErrorText( msg );
2025 memcpy( buf, msg, len );
2028 PR_GetErrorText( buf );
2031 return i ? buf : NULL;
2035 tlsm_session_my_dn( tls_session *session, struct berval *der_dn )
2037 tlsm_session *s = (tlsm_session *)session;
2038 CERTCertificate *cert;
2040 cert = SSL_LocalCertificate( s );
2041 if (!cert) return LDAP_INVALID_CREDENTIALS;
2043 der_dn->bv_val = cert->derSubject.data;
2044 der_dn->bv_len = cert->derSubject.len;
2045 CERT_DestroyCertificate( cert );
2050 tlsm_session_peer_dn( tls_session *session, struct berval *der_dn )
2052 tlsm_session *s = (tlsm_session *)session;
2053 CERTCertificate *cert;
2055 cert = SSL_PeerCertificate( s );
2056 if (!cert) return LDAP_INVALID_CREDENTIALS;
2058 der_dn->bv_val = cert->derSubject.data;
2059 der_dn->bv_len = cert->derSubject.len;
2060 CERT_DestroyCertificate( cert );
2064 /* what kind of hostname were we given? */
2070 tlsm_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
2072 tlsm_session *s = (tlsm_session *)session;
2073 CERTCertificate *cert;
2074 const char *name, *domain = NULL, *ptr;
2075 int i, ret, ntype = IS_DNS, nlen, dlen;
2076 #ifdef LDAP_PF_INET6
2077 struct in6_addr addr;
2079 struct in_addr addr;
2084 if( ldap_int_hostname &&
2085 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
2087 name = ldap_int_hostname;
2091 nlen = strlen( name );
2093 cert = SSL_PeerCertificate( s );
2095 Debug( LDAP_DEBUG_ANY,
2096 "TLS: unable to get peer certificate.\n",
2098 /* if this was a fatal condition, things would have
2099 * aborted long before now.
2101 return LDAP_SUCCESS;
2104 #ifdef LDAP_PF_INET6
2105 if (name[0] == '[' && strchr(name, ']')) {
2106 char *n2 = ldap_strdup(name+1);
2107 *strchr(n2, ']') = 0;
2108 if (inet_pton(AF_INET6, n2, &addr))
2113 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
2114 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
2116 if (ntype == IS_DNS ) {
2117 domain = strchr( name, '.' );
2119 dlen = nlen - ( domain - name );
2122 ret = LDAP_LOCAL_ERROR;
2124 rv = CERT_FindCertExtension( cert, SEC_OID_X509_SUBJECT_ALT_NAME,
2126 if ( rv == SECSuccess && altname.data ) {
2128 CERTGeneralName *names, *cur;
2130 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
2132 ret = LDAP_NO_MEMORY;
2136 names = cur = CERT_DecodeAltNameExtension(arena, &altname);
2145 if ( !cur->name.other.len ) continue;
2147 host = cur->name.other.data;
2148 hlen = cur->name.other.len;
2150 if ( cur->type == certDNSName ) {
2151 if ( ntype != IS_DNS ) continue;
2153 /* is this an exact match? */
2154 if ( nlen == hlen && !strncasecmp( name, host, nlen )) {
2159 /* is this a wildcard match? */
2160 if ( domain && host[0] == '*' && host[1] == '.' &&
2161 dlen == hlen-1 && !strncasecmp( domain, host+1, dlen )) {
2165 } else if ( cur->type == certIPAddress ) {
2166 if ( ntype == IS_DNS ) continue;
2168 #ifdef LDAP_PF_INET6
2169 if (ntype == IS_IP6 && hlen != sizeof(struct in6_addr)) {
2173 if (ntype == IS_IP4 && hlen != sizeof(struct in_addr)) {
2176 if (!memcmp(host, &addr, hlen)) {
2181 } while (( cur = CERT_GetNextGeneralName( cur )) != names );
2183 PORT_FreeArena( arena, PR_FALSE );
2184 SECITEM_FreeItem( &altname, PR_FALSE );
2186 /* no altnames matched, try the CN */
2187 if ( ret != LDAP_SUCCESS ) {
2188 /* find the last CN */
2189 CERTRDN *rdn, **rdns;
2190 CERTAVA *lastava = NULL;
2194 rdns = cert->subject.rdns;
2195 while ( rdns && ( rdn = *rdns++ )) {
2196 CERTAVA *ava, **avas = rdn->avas;
2197 while ( avas && ( ava = *avas++ )) {
2198 if ( CERT_GetAVATag( ava ) == SEC_OID_AVA_COMMON_NAME )
2203 SECItem *av = CERT_DecodeAVAValue( &lastava->value );
2205 if ( av->len == nlen && !strncasecmp( name, av->data, nlen )) {
2207 } else if ( av->data[0] == '*' && av->data[1] == '.' &&
2208 domain && dlen == av->len - 1 && !strncasecmp( name,
2209 av->data+1, dlen )) {
2213 if ( len >= sizeof(buf) )
2214 len = sizeof(buf)-1;
2215 memcpy( buf, av->data, len );
2218 SECITEM_FreeItem( av, PR_TRUE );
2221 if ( ret != LDAP_SUCCESS ) {
2222 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
2223 "common name in certificate (%s).\n",
2225 ret = LDAP_CONNECT_ERROR;
2226 if ( ld->ld_error ) {
2227 LDAP_FREE( ld->ld_error );
2229 ld->ld_error = LDAP_STRDUP(
2230 _("TLS: hostname does not match CN in peer certificate"));
2235 CERT_DestroyCertificate( cert );
2240 tlsm_session_strength( tls_session *session )
2242 tlsm_session *s = (tlsm_session *)session;
2245 rc = SSL_SecurityStatus( s, NULL, NULL, NULL, &keySize,
2247 return rc ? 0 : keySize;
2251 * TLS support for LBER Sockbufs
2254 static PRStatus PR_CALLBACK
2255 tlsm_PR_Close(PRFileDesc *fd)
2257 int rc = PR_SUCCESS;
2259 /* we don't need to actually close anything here, just
2260 pop our io layer off the stack */
2261 fd->secret = NULL; /* must have been freed before calling PR_Close */
2263 fd = PR_PopIOLayer( fd, tlsm_layer_id );
2264 /* if we are not the last layer, pass the close along */
2269 rc = fd->methods->close( fd );
2272 /* we are the last layer - just call our dtor */
2279 static PRStatus PR_CALLBACK
2280 tlsm_PR_Shutdown(PRFileDesc *fd, PRShutdownHow how)
2282 int rc = PR_SUCCESS;
2285 rc = PR_Shutdown( fd->lower, how );
2291 static int PR_CALLBACK
2292 tlsm_PR_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
2293 PRIntervalTime timeout)
2298 if ( buf == NULL || len <= 0 ) return 0;
2300 p = (struct tls_data *)fd->secret;
2302 if ( p == NULL || p->sbiod == NULL ) {
2306 rc = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
2308 tlsm_map_error( errno );
2309 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2310 p->nonblock = PR_TRUE; /* fd is using non-blocking io */
2311 } else if ( errno ) { /* real error */
2312 Debug( LDAP_DEBUG_TRACE,
2313 "TLS: error: tlsm_PR_Recv returned %d - error %d:%s\n",
2314 rc, errno, STRERROR(errno) );
2321 static int PR_CALLBACK
2322 tlsm_PR_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
2323 PRIntervalTime timeout)
2328 if ( buf == NULL || len <= 0 ) return 0;
2330 p = (struct tls_data *)fd->secret;
2332 if ( p == NULL || p->sbiod == NULL ) {
2336 rc = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
2338 tlsm_map_error( errno );
2339 if ( errno == EAGAIN || errno == EWOULDBLOCK ) {
2340 p->nonblock = PR_TRUE;
2341 } else if ( errno ) { /* real error */
2342 Debug( LDAP_DEBUG_TRACE,
2343 "TLS: error: tlsm_PR_Send returned %d - error %d:%s\n",
2344 rc, errno, STRERROR(errno) );
2351 static int PR_CALLBACK
2352 tlsm_PR_Read(PRFileDesc *fd, void *buf, PRInt32 len)
2354 return tlsm_PR_Recv( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2357 static int PR_CALLBACK
2358 tlsm_PR_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
2360 return tlsm_PR_Send( fd, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2363 static PRStatus PR_CALLBACK
2364 tlsm_PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
2370 p = (struct tls_data *)fd->secret;
2372 if ( p == NULL || p->sbiod == NULL ) {
2375 len = sizeof(PRNetAddr);
2376 return getpeername( p->sbiod->sbiod_sb->sb_fd, (struct sockaddr *)addr, &len );
2379 static PRStatus PR_CALLBACK
2380 tlsm_PR_GetSocketOption(PRFileDesc *fd, PRSocketOptionData *data)
2383 p = (struct tls_data *)fd->secret;
2389 /* only the nonblocking option is supported at this time
2390 MozNSS SSL code needs it */
2391 if ( data->option != PR_SockOpt_Nonblocking ) {
2392 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2396 int flags = fcntl( p->sbiod->sbiod_sb->sb_fd, F_GETFL );
2397 data->value.non_blocking = (flags & O_NONBLOCK) ? PR_TRUE : PR_FALSE;
2399 data->value.non_blocking = p->nonblock;
2404 static PRStatus PR_CALLBACK
2407 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2411 static PRFileDesc * PR_CALLBACK
2414 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2418 static PRInt16 PR_CALLBACK
2421 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2425 static PRInt32 PR_CALLBACK
2428 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2432 static PRInt64 PR_CALLBACK
2437 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2442 static const PRIOMethods tlsm_PR_methods = {
2444 tlsm_PR_Close, /* close */
2445 tlsm_PR_Read, /* read */
2446 tlsm_PR_Write, /* write */
2447 tlsm_PR_i32_unimp, /* available */
2448 tlsm_PR_i64_unimp, /* available64 */
2449 tlsm_PR_prs_unimp, /* fsync */
2450 tlsm_PR_i32_unimp, /* seek */
2451 tlsm_PR_i64_unimp, /* seek64 */
2452 tlsm_PR_prs_unimp, /* fileInfo */
2453 tlsm_PR_prs_unimp, /* fileInfo64 */
2454 tlsm_PR_i32_unimp, /* writev */
2455 tlsm_PR_prs_unimp, /* connect */
2456 tlsm_PR_pfd_unimp, /* accept */
2457 tlsm_PR_prs_unimp, /* bind */
2458 tlsm_PR_prs_unimp, /* listen */
2459 (PRShutdownFN)tlsm_PR_Shutdown, /* shutdown */
2460 tlsm_PR_Recv, /* recv */
2461 tlsm_PR_Send, /* send */
2462 tlsm_PR_i32_unimp, /* recvfrom */
2463 tlsm_PR_i32_unimp, /* sendto */
2464 (PRPollFN)tlsm_PR_i16_unimp, /* poll */
2465 tlsm_PR_i32_unimp, /* acceptread */
2466 tlsm_PR_i32_unimp, /* transmitfile */
2467 tlsm_PR_prs_unimp, /* getsockname */
2468 tlsm_PR_GetPeerName, /* getpeername */
2469 tlsm_PR_i32_unimp, /* getsockopt OBSOLETE */
2470 tlsm_PR_i32_unimp, /* setsockopt OBSOLETE */
2471 tlsm_PR_GetSocketOption, /* getsocketoption */
2472 tlsm_PR_i32_unimp, /* setsocketoption */
2473 tlsm_PR_i32_unimp, /* Send a (partial) file with header/trailer*/
2474 (PRConnectcontinueFN)tlsm_PR_prs_unimp, /* connectcontinue */
2475 tlsm_PR_i32_unimp, /* reserved for future use */
2476 tlsm_PR_i32_unimp, /* reserved for future use */
2477 tlsm_PR_i32_unimp, /* reserved for future use */
2478 tlsm_PR_i32_unimp /* reserved for future use */
2482 * Initialize TLS subsystem. Should be called only once.
2483 * See tlsm_deferred_init for the bulk of the init process
2490 tlsm_layer_id = PR_GetUniqueIdentity( "OpenLDAP" );
2496 tlsm_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
2499 tlsm_session *session = arg;
2502 assert( sbiod != NULL );
2504 p = LBER_MALLOC( sizeof( *p ) );
2509 fd = PR_GetIdentitiesLayer( session, tlsm_layer_id );
2515 fd->secret = (PRFilePrivate *)p;
2516 p->session = session;
2518 sbiod->sbiod_pvt = p;
2523 tlsm_sb_remove( Sockbuf_IO_Desc *sbiod )
2527 assert( sbiod != NULL );
2528 assert( sbiod->sbiod_pvt != NULL );
2530 p = (struct tls_data *)sbiod->sbiod_pvt;
2531 PR_Close( p->session );
2532 LBER_FREE( sbiod->sbiod_pvt );
2533 sbiod->sbiod_pvt = NULL;
2538 tlsm_sb_close( Sockbuf_IO_Desc *sbiod )
2542 assert( sbiod != NULL );
2543 assert( sbiod->sbiod_pvt != NULL );
2545 p = (struct tls_data *)sbiod->sbiod_pvt;
2546 PR_Shutdown( p->session, PR_SHUTDOWN_BOTH );
2551 tlsm_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
2555 assert( sbiod != NULL );
2556 assert( sbiod->sbiod_pvt != NULL );
2558 p = (struct tls_data *)sbiod->sbiod_pvt;
2560 if ( opt == LBER_SB_OPT_GET_SSL ) {
2561 *((tlsm_session **)arg) = p->session;
2564 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
2565 if ( tlsm_is_io_ready( p->session, PR_POLL_READ, NULL ) > 0 ) {
2571 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
2575 tlsm_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2581 assert( sbiod != NULL );
2582 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2584 p = (struct tls_data *)sbiod->sbiod_pvt;
2586 ret = PR_Recv( p->session, buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2588 err = PR_GetError();
2589 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2590 sbiod->sbiod_sb->sb_trans_needs_read = 1;
2591 sock_errset(EWOULDBLOCK);
2594 sbiod->sbiod_sb->sb_trans_needs_read = 0;
2600 tlsm_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
2606 assert( sbiod != NULL );
2607 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
2609 p = (struct tls_data *)sbiod->sbiod_pvt;
2611 ret = PR_Send( p->session, (char *)buf, len, 0, PR_INTERVAL_NO_TIMEOUT );
2613 err = PR_GetError();
2614 if ( err == PR_PENDING_INTERRUPT_ERROR || err == PR_WOULD_BLOCK_ERROR ) {
2615 sbiod->sbiod_sb->sb_trans_needs_write = 1;
2616 sock_errset(EWOULDBLOCK);
2620 sbiod->sbiod_sb->sb_trans_needs_write = 0;
2625 static Sockbuf_IO tlsm_sbio =
2627 tlsm_sb_setup, /* sbi_setup */
2628 tlsm_sb_remove, /* sbi_remove */
2629 tlsm_sb_ctrl, /* sbi_ctrl */
2630 tlsm_sb_read, /* sbi_read */
2631 tlsm_sb_write, /* sbi_write */
2632 tlsm_sb_close /* sbi_close */
2635 tls_impl ldap_int_tls_impl = {
2647 tlsm_session_connect,
2648 tlsm_session_accept,
2649 tlsm_session_upflags,
2650 tlsm_session_errmsg,
2652 tlsm_session_peer_dn,
2653 tlsm_session_chkhost,
2654 tlsm_session_strength,
2658 #ifdef LDAP_R_COMPILE
2667 #endif /* HAVE_MOZNSS */